POJ 1706 References (词典)

这里写图片描述

由于以前着这种题没有题解做着非常害怕,因为要做好长好长时间才能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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值