This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
mt19937_64 rng((int)std::chrono::steady_clock::now().time_since_epoch().count());
const int MAXN = 3e5 + 10;
const int MOD = 1e9 + 7;
#define int long long
vector<int> adj[MAXN];
char c[MAXN];
int dp[MAXN];
int dpf(int node, int prev) {
int sum = 0, mx = 0;
for(int x: adj[node]) {
if(x != prev) {
int d = dpf(x, node);
sum += d;
mx = max(mx, d);
}
}
if(prev == -1 && c[node] == '1') {
return dp[node] = max(mx + 1, sum - 1);
}
if(prev == -1 && c[node] == '0') {
return dp[node] = sum;
}
if(c[node] == '1') {
return dp[node] = max(1ll, sum - 1);
}
else {
return dp[node] = sum;
}
}
int ans = 0;
void reroot(int x, int y) {
dp[x] = (c[x] == '1' ? 1 : 0);
int sum = 0, mx = 0;
for(int z: adj[y]) {
sum += dp[z];
mx = max(mx, dp[z]);
}
dp[y] = (c[y] == '1' ? max(mx + 1, sum - 1) : sum);
}
void dfs(int node, int prev) {
ans = max(ans, dp[node]);
for(int x: adj[node]) {
if(x != prev) {
reroot(node, x);
dfs(x, node);
reroot(x, node);
}
}
}
void solve(int tc) {
int N;
cin >> N;
for(int i=1; i<N; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
if(N == 1) {
cout << "1\n"; return;
}
for(int i=1; i<=N; i++) cin >> c[i];
dpf(1, -1);
dfs(1, -1);
cout << ans << "\n";
}
int32_t main(){
ios::sync_with_stdio(0); cin.tie(0);
int t = 1; //cin >> t;
for(int i=1; i<=t; i++) solve(i);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |