Hoj 3029 Dictionary

来源:互联网 发布:淘宝 梦之蓝舞蹈服饰 编辑:程序博客网 时间:2024/04/28 16:36

题目连接:http://acm.hit.edu.cn/hoj/problem/view?id=3029

题目是一个XML格式的文本,要筛选出相应缩进的词条。

可以用栈来模拟这个过程。type = 0表示内容,1表示起始,2表示结束,其中1和2是对应关系。cur记录当前的缩进变化。

如:范例中的XML格式的type分别是101021102102202

另外注意string不能用scanf()读入,用char[]吧。结构体初始化时再转换成string较好。

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <math.h>#include <algorithm>#include <stack>#include <queue>using namespace std;struct Word{    string str;    int type;    int offset;    Word(){};    Word(string s)    {        if(s[0]!='<')        {            type = 0;            str = s;        }        else if(s[1] == '/')        {            type = 2;            str = s.substr(2,s.length()-3);        }        else        {            type = 1;            str = s.substr(1,s.length() - 4);            offset = s[s.length()-2] - '0';        }    }};int main(){#ifndef ONLINE_JUDGE    freopen("in.txt","r",stdin);#endif    int n,q;    char c[105];    while(scanf(" %d %d",&n,&q)!=EOF)    {        stack<Word> s;        queue<Word> result;        int cur = 0;        int count = 0;        for(int i=0;i<n;i++)        {            scanf(" %[^\n]s",c);//别忘了前面加个空格            Word a(c);            if(a.type == 1)            {                s.push(a);                cur += a.offset;                if(cur == q)                {                    count ++;                    result.push(a);                }            }            else if(a.type == 2)            {                cur -= s.top().offset;//这里犯过错误,原来写成了cur-+a.offset;                s.pop();            }            getchar();        }        printf("%d\n",count);        while(!result.empty())        {            printf("%s\n",result.front().str.c_str());            result.pop();        }    }    return 0;}


原创粉丝点击