-
Notifications
You must be signed in to change notification settings - Fork 66
/
74-Tree with Maximum Cost.cpp
57 lines (56 loc) · 1.09 KB
/
74-Tree with Maximum Cost.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
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>>v;
vector<long long>sub,dp,ans;
void dfs_1(int x,int p,vector<int> a)
{
sub[x]=a[x-1];
for(auto itr:v[x])
{
if(itr!=p)
{
dfs_1(itr,x,a);
sub[x]+=sub[itr];
dp[x]+=dp[itr]+sub[itr];
}
}
}
void dfs(int x,int p)
{
long long par;
if(p!=0)
{
par=ans[p]-dp[x]-sub[x];
ans[x]=par+dp[x]+sub[1]-sub[x];
}
for(auto itr:v[x])
{
if(itr!=p)
{
dfs(itr,x);
}
}
}
long long treeMaxCost(int n, vector<int> a ,vector<vector<int>> edges)
{
v=vector<vector<int>>(n+1,vector<int>());
sub.assign(n+1,0);
ans.assign(n+1,0);
dp.assign(n+1,0);
long long x,y,val;
for(int i=0;i<n-1;i++)
{
x=edges[i][0],y=edges[i][1];
v[x].push_back(y);
v[y].push_back(x);
}
dfs_1(1,0,a);
ans[1]=dp[1];
dfs(1,0);
val=0;
for(int i=1;i<=n;i++)
{
val=max(val,ans[i]);
}
return val;
}