我的做法有点神奇,打字说不出来,直接看代码。(如果有不懂的地方我可以回复来解答)
//
// Created by nkrq009/AsoltA on 2023/3/29.
//
#include <bits/stdc++.h>
#define cin std::cin
#define cout std::cout
#define string std::string
#define pair std::pair
#define mkp std::make_pair
int n,cnt,cntu,ff[105],ed[105],eu[105],usedef[105][105];
string code[105],st,nn,ans;
pair<string,string> def[105];
string undef[105];
string subreplace(string resource_str,string sub_str,string new_str)
{
string dst_str=std::move(resource_str);
string::size_type pos;
while((pos=dst_str.find(sub_str))!=string::npos)
{
dst_str.replace(pos, sub_str.length(), new_str);
}
return dst_str;
}
signed main()
{
cin>>n;
string hhh="\n";
getline(cin,hhh);
for(int i=1;i<=n;i++)
{
string x;
getline(cin,x);
code[i]=x;
nn=nn+'\n'+x;
if(x[0]=='#'&&x[1]=='d')
{
string y,z;
x=x.substr(8);
int d=x.find(' ');
y=x.substr(0,d);
z=x.substr(d+1);
def[++cnt]=mkp(y,z);
ff[i]=1;
ed[i]=cnt;
}
else if(x[0]=='#'&&x[1]=='u')
{
x=x.substr(7);
undef[++cntu]=x;
ff[i]=2;
eu[i]=cntu;
}
}
while(true)
{
st.clear();
std::list<pair<pair<string,string>,int>> defs;
for(int i=1;i<=n;i++)
{
if(ff[i]==1)
{
defs.emplace_back(mkp(def[ed[i]],ed[i]));
continue;
}
if(ff[i]==2)
{
for(auto x=defs.begin();x!=defs.end();x++)
{
if((*x).first.first==undef[eu[i]])
{
defs.erase(x);
break;
}
}
continue;
}
for(auto & x : defs)
{
string dd=subreplace(code[i],x.first.first,x.first.second);
if(dd!=code[i])
{
if(usedef[i][x.second])
{
break;
}
else
{
usedef[i][x.second]=1;
code[i]=dd;
}
}
}
st=st+'\n'+code[i];
}
if(nn==st)
{
break;
}
nn=st;
}
for(int i=1;i<=n;i++)
{
if(ff[i]>0)
{
cout<<std::endl;
}
else
{
cout<<code[i]<<std::endl;
}
}
return 0;
}