-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCutTheTree.cpp
66 lines (48 loc) · 927 Bytes
/
CutTheTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// problem: "https://www.hackerrank.com/challenges/cut-the-tree/problem"
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;
vector<int>V(100001,0);
vector<int>SS(100001,0);
vector<int> data;
int SumSubtree(vector<int>G[],int i)
{
if(V[i]==1)
return 0;
V[i] = 1;
int j;
for(j=0;j!=G[i].size();j++)
SS[i] += SumSubtree(G,G[i][j]);
SS[i] += data[i-1];
return SS[i];
}
int main()
{
int n;
cin>>n;
int i;
for(i=0;i!=n;i++)
{
int x;
cin>>x;
data.push_back(x);
}
vector<int>G[n+1];
for(i=0;i!=n;i++)
{
int x,y;
cin>>x>>y;
G[x].push_back(y);
G[y].push_back(x);
}
int T = SumSubtree(G,1); // define function
int m = T;
for(i=2;i!=n+1;i++)
{
if(abs(2*SS[i]-T) < m)
m = abs(2*SS[i]-T);
}
cout<<m;
return 0;
}