UVA 10410(p180)----Tree Reconstruction

#include<bits/stdc++.h>
#define debu
using namespace std;
const int maxn=1010;
int n,root,v;
int d[maxn];
stack<int> s;
vector<int> g[maxn];
int main()
{
#ifdef debug
    freopen("in.in","r",stdin);
#endif // debug
    while(scanf("%d",&n)!=EOF)
    {
        memset(d,0,sizeof(d));
        while(!s.empty()) s.pop();
        for(int i=0; i<n; i++)
        {
            int x;
            scanf("%d",&x);
            g[x].clear();
            d[x]=i;
        }
        scanf("%d",&root);
        s.push(root);
        for(int i=1; i<n; i++)
        {
            scanf("%d",&v);
            while(1)
            {
                int u=s.top();
                if(u==root||d[v]>d[u]+1)
                {
                    s.push(v);
                    g[u].push_back(v);
                    break;
                }
                else s.pop();
            }
        }
        for(int i=1; i<=n; i++)
        {
            printf("%d:",i);
            for(int j=0; j<g[i].size(); j++)
                printf(" %d",g[i][j]);
            printf("\n");
        }
    }
    return 0;
}

你可能感兴趣的:(UVA 10410(p180)----Tree Reconstruction)