1. 程式人生 > >UVA 10410 Tree Reconstruction

UVA 10410 Tree Reconstruction

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int size=1010;

int n,ord[size],dfs[size],bfs[size],deep[size],vis[size];
vector <int> arr[size];
queue <int> q;

int check(int a,int b,int curDeep){
	int i,e=dfs[a],f=dfs[b],c=ord[e],d=ord[f];
	for(i=a+1;i<b;i++){
		int tmp=dfs[i];
		if(deep[tmp]==0)
			continue;
		if(deep[tmp]!=curDeep)
			return 0;
	}
	for(i=c+1;i<d;i++){
		int tmp=bfs[i];
		if(!vis[tmp])
			return 0;
	}
	return 1;
}

void cal(int cur,int curDeep){
	int cnt=dfs[cur],i;
	for(i=cur+1;i<n;i++){
		int tmp=dfs[i];
		if(vis[tmp])
			continue;
		if(check(cur, i, curDeep+1))
			arr[cnt].push_back(tmp);
		else
			continue;
		q.push(i);
		vis[tmp]=1;
		deep[tmp]=curDeep+1;
	}
}

void print(){
	int i,j;
	for(i=1;i<=n;i++){
		printf("%d:",i);
		for(j=0;j<arr[i].size();j++)
			printf(" %d",arr[i][j]);
		puts("");
	}
}

int main(){
	int i,j;
	while(scanf("%d",&n)!=EOF){
		memset(vis,0,sizeof(vis));
		memset(deep,0,sizeof(deep));
		memset(ord,0,sizeof(ord));
		memset(dfs,0,sizeof(dfs));
		memset(bfs,0,sizeof(bfs));
		for(i=0;i<=n;i++)
			arr[i].clear();
		while(!q.empty())
			q.pop();
		for(i=0;i<n;i++){
			int t;
			scanf("%d",&t);
			bfs[i]=t;
			ord[t]=i;
		}
		for(i=0;i<n;i++)
			scanf("%d",&dfs[i]);
		deep[dfs[0]]=1;
		q.push(0);
		while(!q.empty()){
			int cnt=q.front();
			q.pop();
			cal(cnt,deep[dfs[cnt]]);
		}
		print();
	}
	return 0;
}