hdu 4041 Eliminate Witches! (栈的模拟)

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

题目考查:模拟。

很悲剧的一道题,这个题是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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值