递归遍历树,DFS
/*******************************************************************************
# Author : Neo Fung
# Email : neosfung@gmail.com
# Last modified: 2012-01-16 17:58
# Filename: ZOJ3516 Tree of Three.cpp
# Description :
******************************************************************************/
#ifdef _MSC_VER
#define DEBUG
#endif
#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
#include <limits.h>
#include <algorithm>
#include <math.h>
#include <numeric>
#include <functional>
#include <ctype.h>
#define MAX 10010
using namespace std;
struct NODE
{
int ind;
NODE *next;
}node[MAX],*head[MAX];
int value[MAX];
int cnt;
void init(const int &n)
{
cnt=0;
memset(head,'\0',sizeof(head));
for(int i=0;i<n;++i)
value[i]=INT_MIN;
}
void add(const int &father,const int &ind,const int &v)
{
node[cnt].ind=ind;
node[cnt].next = head[father];
head[father] = &node[cnt++];
value[ind] = v;
}
void dfs(const int &root,int &sum,int *max_3)
{
max_3[sum++] = value[root];
sort(max_3,max_3+sum,greater<int>());
sum=min(sum,3);
if(head[root]==NULL)
return ;
NODE *p=head[root];
while(p)
{
dfs(p->ind,sum,max_3);
p=p->next;
}
}
int main(void)
{
#ifdef DEBUG
freopen("../stdin.txt","r",stdin);
freopen("../stdout.txt","w",stdout);
#endif
int n,m;
int val,father,result[4];
while(~scanf("%d",&n))
{
init(n);
scanf("%d",&value[0]);
for(int i=1;i<n;++i)
{
scanf("%d%d",&father,&val);
add(father,i,val);
}
scanf("%d",&m);
while(m--)
{
scanf("%d",&father);
for(int i=0;i<4;++i)
result[i]=INT_MIN;
int sum=0;
dfs(father,sum,result);
if(result[2]==INT_MIN)
printf("-1\n");
else
printf("%d %d %d\n",result[0],result[1],result[2]);
}
}
return 0;
}