Http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemid = 4381
Contest:Zoj monthly, July 2011
Give you a tree, 10000 nodes, each node has a weight value, tell you the weight value of each node and Father's Day point, and then 10000 queries, query the maximum three values of the subtree with each node as the root. If the value is smaller than three output values-1.
I don't want to save my son nodes, so I saved the Father's Day points for each node. I scanned all the nodes each time and sent the leaf nodes up... Note that in order to avoid too many scans, if a node does not have a son node on Father's Day, the node will be sent directly to the parent node... (In some special cases, it is still 3*10 ^ 7)
The best solution is to use a vector to store the son node, and then a DFS is enough ..... You can be arrogant about a tree DFS...
Code:
#include<iostream>#include<algorithm>#include<stdio.h>#include<memory.h>using namespace std;const int N=10010;int m, n;struct node{int parent;int sonnum, cnt, a[3];void init(){sonnum = 0;cnt = 1;}} a[N];int cmp(int a, int b){return a>b;}void fun(int i){int l, k, j = a[i].parent;int b[6], bn;bn = 0;for(k=0; k<a[i].cnt; k++)b[bn++] = a[i].a[k];for(k=0; k<a[j].cnt; k++)b[bn++] = a[j].a[k];sort(b, b+bn, cmp);if(bn<=3)a[j].cnt = bn;elsea[j].cnt = 3;for(k=0; k<a[j].cnt; k++)a[j].a[k] = b[k];a[j].sonnum--;}int main(){int i, j, k, cas1=1, flag;while(scanf("%d", &n)!=EOF){for(i=0; i<n; i++)a[i].init();scanf("%d", &a[0].a[0]);for(i=1; i<n; i++){scanf("%d%d", &a[i].parent, &a[i].a[0]);j = a[i].parent;a[j].sonnum++;}flag = 1;while(flag){for(i=1; i<n; i++){j = i;while(j!=0 && a[j].sonnum==0 && a[j].parent!=-1){flag = 0;fun(j);k = j;j = a[j].parent;a[k].parent = -1;}}if(flag==0)flag = 1;elsebreak;}//printf("Case #%d:\n", cas1++);scanf("%d", &m);while(m--){scanf("%d", &i);if(a[i].cnt<3)printf("-1\n");elseprintf("%d %d %d\n", a[i].a[0], a[i].a[1], a[i].a[2]);}}return 0;}