题意:给定一颗树的BFS和DFS,求这棵的每个节点。
思路:用栈模拟维护。对应的BFS为每个节点到根节点的距离,然后比较当前节点和栈顶节点与根的距离,如果当前节点大,则为栈顶节点的孩子,否则弹出继续比较。
code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const int INF=0x3fffffff;
const int inf=-INF;
const int N=1000005;
const int M=1005;
const int mod=1000000007;
const double pi=acos(-1.0);
#define cls(x,c) memset(x,c,sizeof(x))
#define fr(i,s,n) for (int i=s;i<=n;i++)
int v[M];
vector<int>p[M];
stack<int>s;
void sol(int q)
{
while (1)
{
if (v[q]==2||v[q]>1+v[s.top()])
{
p[s.top()].push_back(q),s.push(q);
break;
}
else s.pop();
}
}
int main()
{
int n,x;
while (~scanf("%d",&n)&&n)
{
fr(i,1,n) scanf("%d",&x),v[x]=i,p[i].clear();
scanf("%d",&x); s.push(x);
fr(i,1,n-1) {scanf("%d",&x);sol(x);}
fr (i,1,n)
{
printf("%d:",i);
for (int j=0;j<p[i].size();j++)
printf(" %d",p[i][j]);
puts("");
}
while (!s.empty()) s.pop();
}
}