Skip to content

Commit 8c42fbd

Browse files
authored
Create 2019-F-C.cpp
1 parent 875e616 commit 8c42fbd

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

kick-start/2019-F-C.cpp

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
#include<bits/stdc++.h>
2+
#define ms(x,v) memset((x),v,sizeof(x))
3+
#define INF 0x3f3f3f3f
4+
using namespace std;
5+
6+
const int MAXN = 2e5+10;
7+
typedef long long LL;
8+
9+
unordered_map<int,LL> dp;
10+
11+
vector<int> G[MAXN];
12+
int b[MAXN];
13+
14+
inline int encode(int pc,int vc){
15+
return (vc<<1) | (pc);
16+
}
17+
18+
LL dfs(int u,int v,int s){
19+
if(dp.count((v<<2)|s))
20+
return dp[(v<<2)|s];
21+
22+
int pc = s&1;
23+
int vc = (s>>1) & 1;
24+
LL ans =0;
25+
if(s>0){// color this node
26+
ans += b[v];
27+
for(auto e : G[v]){
28+
if(e == u)continue;
29+
ans += max(dfs(v,e,encode(vc,0)),dfs(v,e,encode(vc,1)));
30+
}
31+
}else{
32+
vector<vector<int> > ansdp(G[v].size(),vector<int>(2,0));
33+
int i =-1;
34+
for(auto e : G[v]){
35+
if(e == u)continue;
36+
if(i==-1){
37+
i=0;
38+
ansdp[0][0] = dfs(v,e,encode(vc,0));
39+
ansdp[0][1] = dfs(v,e,encode(vc,1));
40+
}else{
41+
assert(i>0);
42+
ansdp[i][0] = ansdp[i-1][0] + dfs(v,e,encode(vc,0));
43+
ansdp[i][1] = max(ansdp[i-1][1]+max(dfs(v,e,encode(vc,0)),dfs(v,e,encode(vc,1)))
44+
,ansdp[i-1][0]+dfs(v,e,encode(vc,1)));
45+
}
46+
i++;
47+
}
48+
if(i==-1)ans =0;
49+
else
50+
ans = max(ansdp[i-1][0],ansdp[i-1][1]+b[v]);
51+
}
52+
dp[(v<<2)|s] = ans;
53+
return ans;
54+
}
55+
56+
void solve(){
57+
int N;
58+
cin >> N;
59+
for(int i=0 ; i<N ; ++i)cin >> b[i];
60+
for(int i=1 ; i<N ; ++i){
61+
int x,y;
62+
cin >> x >> y;
63+
x--,y--;
64+
G[x].push_back(y);
65+
G[y].push_back(x);
66+
}
67+
68+
cout << max(dfs(-1,0,encode(0,0)),dfs(-1,0,encode(0,1))) << "\n";
69+
dp.clear();
70+
for(int i=0 ; i<N ; ++i)G[i].clear();
71+
}
72+
73+
74+
75+
76+
int main(){
77+
ios :: sync_with_stdio(0);
78+
cin.tie(0);
79+
// cout.tie(0);
80+
std::cout.precision(10);
81+
std::cout.setf( std::ios::fixed, std:: ios::floatfield );
82+
83+
int T;
84+
cin >> T;
85+
for(int tt =1 ; tt <=T ; ++tt)
86+
{
87+
cout << "Case #" << tt << ": ";
88+
solve();
89+
}
90+
91+
92+
return 0;
93+
}

0 commit comments

Comments
 (0)