ZOJ3516 Tree of Three

递归遍历树,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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值