思路:深度优先搜索,一层一层由子节点向跟节点回溯。
1.
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define MAX 11111
using namespace std;
int Three_Max[MAX][15], val[MAX], cnt[MAX];
typedef struct{
int to, next;
}Node;
Node edge[MAX];
int head[MAX];
void AddEdge(int u, int v, int i){
edge[i].to = v;
edge[i].next = head[u];
head[u] = i;
}
bool cmp(int a, int b){
return a > b;
}
void dfs(int id){
cnt[id] = 1;
Three_Max[id][1] = val[id];
for(int i = head[id];i != -1;i = edge[i].next){
int u = edge[i].to;
dfs(u);
for(int j = 4;j <= 6;j ++) Three_Max[id][j] = Three_Max[u][j-3];
sort(Three_Max[id] + 1, Three_Max[id]+10, cmp);
cnt[id] += cnt[u];
}
}
int main(){
int n, m, cc, u, v, k;
while(~scanf("%d", &n)){
memset(head, -1, sizeof(head));
memset(Three_Max, 0, sizeof(Three_Max));
memset(cnt, 0, sizeof(cnt));
k = 1;
for(int i = 0;i < n;i ++){
if(0 == i){
scanf("%d", &cc);
val[0] = cc;
}else{
scanf("%d%d", &u, &cc);
val[i] = cc;
AddEdge(u, i, k);
k ++;
}
}
dfs(0);
scanf("%d", &m);
for(int i = 0;i < m;i ++){
scanf("%d", &u);
if(cnt[u] < 3) printf("-1\n");
else{
for(int j = 1;j < 3;j ++) printf("%d ", Three_Max[u][j]);
printf("%d\n", Three_Max[u][3]);
}
}
}
return 0;
}
2.
#include<iostream>
#include<climits>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define MAX 11111
using namespace std;
int Three_Max[MAX][15], val[MAX], cnt[MAX];
typedef struct{
int to, next;
}Node;
Node edge[MAX];
int head[MAX];
void AddEdge(int u, int v, int i){
edge[i].to = v;
edge[i].next = head[u];
head[u] = i;
}
bool cmp(int a, int b){
return a > b;
}
int *dfs(int id){
cnt[id] = 1;
Three_Max[id][1] = val[id];
for(int i = head[id];i != -1;i = edge[i].next){
int u = edge[i].to;
int *temp = dfs(u);
for(int j = 4;j <= 6;j ++) Three_Max[id][j] = temp[j-3];
sort(Three_Max[id] + 1, Three_Max[id]+10, cmp);
cnt[id] += cnt[u];
}
return Three_Max[id];
}
int main(){
int n, m, cc, u, v, k;
while(~scanf("%d", &n)){
memset(head, -1, sizeof(head));
memset(Three_Max, 0, sizeof(Three_Max));
memset(cnt, 0, sizeof(cnt));
k = 1;
for(int i = 0;i < n;i ++){
if(0 == i){
scanf("%d", &cc);
val[0] = cc;
}else{
scanf("%d%d", &u, &cc);
val[i] = cc;
AddEdge(u, i, k);
k ++;
}
}
dfs(0);
scanf("%d", &m);
for(int i = 0;i < m;i ++){
scanf("%d", &u);
if(cnt[u] < 3) printf("-1\n");
else{
for(int j = 1;j < 3;j ++) printf("%d ", Three_Max[u][j]);
printf("%d\n", Three_Max[u][3]);
}
}
}
return 0;
}