由于以前着这种题没有题解做着非常害怕,因为要做好长好长时间才能AC,或许都AC不了,
所以这次顺着解题报告下来的,虽然没有自己AC的收获大,但也相当不错。
1.懂得了ssscanf还能这么用
2.懂得了c_str()函数是将string转换为char类型。
3.懂得了gets到文件结束不能用EOF,得用NULL;
4.懂得了做这种模拟题逻辑条理必须相当清晰,很多都可以直接写一个函数下次直接套用。
5.懂得了string还能跟char类型的数组进行相加。
要想对本题更清晰,可参考吴永辉数据结构174页。
#include <cstdio>
#include <string.h>
#include <ctype.h>
#include <string>
#include<cctype>
#include<algorithm>
using namespace std;
const int maxn=1000;
const int maxcol=80+5;
struct node
{
string desc;
int oldno;
int newno;
}p[maxn];
int refcnt,refsort;
bool cmp(const node& a,const node& b)
{
return a.newno<b.newno;
}
bool isblack(char s[])
{
for(int i=0;s[i];i++)
if(!isspace(s[i]))
return false;
return true;
}
int getrefno(char s[],int st=1)
{
int refno;
sscanf(s+st,"%d",&refno);
return refno;
}
int searchref(int oldno)
{
for(int i=0;i<refcnt;i++)
if(p[i].oldno==oldno)
return i;
return -1;
}
int insertref(string desc,int oldno)
{
int cur=searchref(oldno);
if(cur<0)
{
cur=refcnt++;
p[cur].newno=0;
}
p[cur].desc=desc;
p[cur].oldno=oldno;
return cur;
}
int getrenewno(int oldno)
{
int k=searchref(oldno);
if(k<0)
k=insertref("",oldno);
if(!p[k].newno)
p[k].newno=++refsort;
return p[k].newno;
}
void proc(char s[])
{
int len=strlen(s);
for(int i=0;i<len;i++)
{
if(s[i]=='[')
{
int oldno=getrefno(s,i+1);
int newno=getrenewno(oldno);
printf("[%d]",newno);
while(s[++i]!=']');
}
else
putchar(s[i]);
}
putchar('\n');
}
int main()
{
refcnt=refsort=0;
char s[maxcol];
while(gets(s)!=NULL)
{
while(isblack(s))
if(gets(s)==NULL)
break;
if(isblack(s))
break;
if(s[0]=='[')
{
int oldno=getrefno(s);
string desc;
do{
desc+=s;
desc+='\n';
}while(gets(s)!=NULL&&!isblack(s));
insertref(desc,oldno);
}
else
{
do{
proc(s);
}while(gets(s)!=NULL&&!isblack(s));
putchar('\n');
}
}
sort(p,p+refcnt,cmp);
for(int i=0;i<refcnt;i++)
{
printf("[%d]",p[i].newno);
int k=0;
while(p[i].desc[k++]!=']');
printf("%s\n",p[i].desc.c_str()+k);
}
return 0;
}