现在的位置: 首页 > 综合 > 正文

【栈+模拟】The 36th ACM/ICPC Asia Regional Beijing Site Online Contest – B Eliminate Witches!

2013年08月28日 ⁄ 综合 ⁄ 共 1161字 ⁄ 字号 评论关闭

栈模拟,当遇到“(”,栈塞入左右两个人名标号;当遇到“)”,删除栈顶元素作为x,此时的栈顶元素作为y;当遇到“,”,比“)”多一步操作,就是把栈顶元素作为x,逗号右边名字标号作为y,并且把右边标号塞入栈。。。

ps:把那句清空栈的语句注释掉时间更少,hdu 93ms,bupt 71ms,均排到前10!!!orz

#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <time.h>
#include <cstdio>
#include <math.h>
#include <iomanip>
#include <cstdlib>
#include <limits.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;

#define N 1000010
#define FRE freopen("a.txt","r",stdin)
char str[N];
char name[50005][12];
struct node{
    int x,y;
}ans[100010];
stack<int> s;
int main(){
    int t;
    scanf("%d",&t);
    getchar();
    while(t--){
        gets(str);
        int i=0,j;
        int len=strlen(str);
        int n=1,m=0;
        int cnt=1;
        //while(!s.empty())s.pop();
        s.push(1);
        while(i<len){
            if(str[i]>='a' && str[i]<='z'){
                while(str[i]>='a' && str[i]<='z'){
                    name[n][m++]=str[i];
                    i++;
                }
                name[n][m]='\0';
                n++;
            }
            else{m=0;
                if(str[i]=='('){
                   s.push(n);
                   ans[cnt].x=n-1;
                   ans[cnt].y=n;
                   cnt++;
                   i++;
                }
                else{
                    int xx=s.top();
                    s.pop();
                    ans[cnt].x=xx;
                    ans[cnt].y=s.top();
                    cnt++;
                    if(str[i]==','){
                        ans[cnt].x=s.top();
                        ans[cnt].y=n;
                        cnt++;
                        s.push(n);
                    }
                    i++;

                }
            }
        }
        printf("%d\n",n-1);
        for(i=1;i<n;i++)
        printf("%s\n",name[i]);
        for(i=1;i<cnt;i++)
        printf("%d %d\n",ans[i].x,ans[i].y);
        puts("");
    }
    return 0;
}

 

抱歉!评论已关闭.