hdu 4041 Eliminate Witches! (栈的模拟)

来源:互联网 发布:web数据挖掘的分类 编辑:程序博客网 时间:2024/05/16 07:48

原题友情链接~快速通道~查看原题请点击此处~

题目考查:模拟。

很悲剧的一道题,这个题是2011年北京赛区网络赛的一道签到题。周赛的时候一看到括号,立马想到了数据结构中的广义表。确实是广义表的形式,也想到了用栈来模拟。然后,就没有然后了,果断悲剧了,水题一道,半天写不出来。代码能力有待提高!

其实还有一种方法是看题目给的图就知道,很明显是DFS的顺序,要是用DFS来解的话唯一的问题就是建树了。

这里我用的是模拟栈来实现的。具体实现看代码,可能有点乱= =,请各位见谅。

#include<iostream>#include<cstdio>#include<cstring>#include<stack>using namespace std;const int nMaxsize = 1000010;const int cntMaxsize = 50010;stack<int>s;int main(){    char str[nMaxsize],data[cntMaxsize][20];    int ncase;    scanf("%d",&ncase);    while(ncase--)    {        scanf("%s",str);        int k = 1 , j = 0;        for(int i = 0 ; str[i]!='\0' ; i++)/*先对字符串中的单词进行提取*/        {            if(str[i] >= 'a' && str[i] <= 'z')            {                data[k][j++] = str[i];            }            if(str[i] == '(' || str[i] == ')' || str[i] == ',' )            {                if(str[i-1] >= 'a' && str[i-1] <= 'z')                {                    k++;                    j = 0;                }            }        }        if(k == 1)        {            k++;        }        cout<<k-1<<endl;        for(int i = 1 ; i < k ; i++)        {            printf("%s\n",data[i]);        }        k = 1;/*配合下面再进行一次括号匹配的扫描*/        s.push(1);        for(int i = 0 ; str[i]!='\0' ; i++)        {            if(str[i] == '(' || str[i] == ')' || str[i] == ',' )            {                if(str[i-1] >= 'a' && str[i-1] <= 'z')                {                    k++;                }                if(str[i] == '(')/*模拟栈*/                {                    int ans = s.top();                    s.push(k);                    printf("%d %d\n",ans,s.top());                }                else if(str[i] == ',')                {                    int ans = s.top();                    s.pop();                    printf("%d %d\n",ans,s.top());                    ans = s.top();                    s.push(k);                    printf("%d %d\n",ans,s.top());                }                else if(str[i] == ')')                {                    int ans = s.top();                    s.pop();                    printf("%d %d\n",ans,s.top());                }            }        }        cout<<endl;        memset(data,0,sizeof(data));/*多组数据,初始化*/    }    return 0;}