CodeForces 747E Comments

栈,模拟。

手动写一个栈模拟一下过程即可。

#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
#include<set>
#include<stack>
#include<iostream>
using namespace std;

char t[1000010];
struct X
{
    string name;
    int son;
}s[1000010];

char tmp[1000010];
int cnt;
int num;

vector<string> ans[1000010];

stack<int>k;

int max_dep,now_dep;
int len,p=-1,sz;

bool wu()
{
    if(p==len-1) return 1;
    return 0;
}

void add()
{
    p++; cnt=0;
    while(1)
    {
        if(t[p]==',') break;
        tmp[cnt++] = t[p++];
    }
    tmp[cnt]=0;

    p++; num=0;
    while(1)
    {
        if(t[p]==',') break;
        num=num*10+t[p]-'0';
        p++;
    }

    s[sz].name = tmp;
    s[sz].son = num;
    sz++;
}

void Push(int x)
{
    if(k.empty()) k.push(x);
    else
    {
        int Top=k.top();
        s[Top].son--;
        k.push(x);
    }
    now_dep++;
    max_dep = max(max_dep,now_dep);
    ans[now_dep].push_back(s[x].name);
}

void Pop()
{
    while(1)
    {
        if(k.empty()) break;
        int Top=k.top();
        if(s[Top].son==0)
        {
            now_dep--;
            k.pop();
        }
        else break;
    }
}

int main()
{
    scanf("%s",t); len=strlen(t);
    t[len]=','; len++; t[len]=0;

    while(1)
    {
        if(wu()) break;
        add();
        Push(sz-1);
        Pop();
    }

    cout<<max_dep<<endl;
    for(int i=1;i<=max_dep;i++)
    {
        for(int j=0;j<ans[i].size();j++)
        {
            cout<<ans[i][j]<<" ";
        }
        cout<<endl;
    }

    return 0;
}

 

posted @ 2016-12-30 09:21  Fighting_Heart  阅读(288)  评论(0编辑  收藏  举报