Hackerrank-cut the Tree

Source: Internet
Author: User

Typical tree recursion works. The key Is:any node can be treated as the root, since it was about edge and not on node. This simplifies things a lot.

#include <cmath>#include<cstdio>#include<vector>#include<iostream>#include<algorithm>#include<unordered_set>using namespaceStd;typedefLong Longlong64;structnode{Node (): Val (0{} Node (unsigned v): Val (v) {} long64 val; Unordered_set<int>Inx;}; LONG64 ret= std::numeric_limits<unsigned>:: Max (); long64 Go (Vector<Node> &nodes,introot, long64 tsum) {Node&n =Nodes[root]; long64 Currsum=N.val;  for(intI:n.inx)        {nodes[i].inx.erase (root); Currsum+=Go (nodes, I, tsum); } ret= Std::min (Std::abs (Tsum-2*currsum), ret); returncurrsum;}intMain () {intN CIN >>N; Vector<Node>nodes (n); long64 sum=0;  for(inti =0; I < n; i++) {unsigned v; CIN>>v; Sum+=v; Nodes[i].val=v; }     for(inti =0; I < n-1; i++)    {        intPi, CI; Cin >> Pi >>CI; Nodes[pi-1].inx.insert (CI-1); Nodes[ci-1].inx.insert (PI-1); } Go (nodes,0, sum); cout<< ret <<Endl; return 0;}

Hackerrank-cut the Tree

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.