Zoj3516 related to trees

Source: Internet
Author: User

 

 

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;}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.