forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS
More file actions
52 lines (50 loc) · 897 Bytes
/
DFS
File metadata and controls
52 lines (50 loc) · 897 Bytes
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
#include <bits stdc++.h="">
using namespace std;
#define ll long long
#define ld long double
const int M = 1e9 + 7;
const ll MAX_WATER_IN_CITY = 1e18+1;
int n, s, *cap;
bool overDemand = false;
vector<vector<int>> e;
bool vis[100001];
ll int maxReq(int node){
ll int max=0;int c=0;vis[node]=true;
for(auto x:e[node]){
if(!vis[x]){c++;
ll int t=maxReq(x);max=max>t?max:t;}
}
ll int ans = cap[node] + max*c;
if (ans > MAX_WATER_IN_CITY || ans < 0) {
overDemand = true;
return 0; }
return ans; }
int main()
{
int t = 0;
cin >> t;
while (t--)
{
cin >> n >> s;
s--;memset(vis,false,n);
cap = new int[n + 1];
e.clear();
e.resize(n + 1, vector<int>());
for (int i = 0; i < n; i++)
{
cin >> cap[i];
}
for (int i = 0; i < n - 1; i++)
{
int x, y;
cin >> x >> y;
x--;
y--;
e[x].push_back(y);
e[y].push_back(x);
}
ll int ans = maxReq(s);
overDemand ? cout << -1 << endl : cout << ans << endl;
}
return 0;
}