This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
using ll = long long; using pii = pair<ll,ll>;
const ll INF = 1e9;
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
ll N; cin >> N;
ll ans = -INF;
vector<ll> adj[N];
vector<ll> fadj[N];
for (ll i=0;i<(N-1);i++) {
ll a,b; cin >> a >> b;
a--; b--;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<bool> found(N,false);
vector<ll> radj(N,-1);
queue<ll> q0;
q0.push(0);
ll fdegL[N];
queue<ll> q1;
while (!q0.empty()) {
ll x = q0.front(); q0.pop();
for (ll y: adj[x]) {
if (y != radj[x]) {
fadj[x].push_back(y);
radj[y]=x;
q0.push(y);
}
}
fdegL[x]=fadj[x].size();
if (fdegL[x]==0) {
q1.push(x);
}
}
bool S[N];
string s1; cin >> s1;
for (ll i=0;i<N;i++) {
if (s1[i]=='1') {
S[i]=1;
} else {
assert(s1[i]=='0');
S[i]=0;
}
}
ll dp0[N]; //dp on: you know that it has to connect down; given that it
//does this, what is the max value?
ll dp1[N]; //does not connect down; what's the max value?
while (!q1.empty()) {
ll x = q1.front(); q1.pop();
if (fadj[x].size()==0) {
dp0[x]=-INF;
dp1[x]=S[x];
} else {
dp1[x]=S[x];
ll mx=-INF; ll sm=0; //max and sum
for (ll y: fadj[x]) {
ll vy = max(dp1[y],dp0[y]);
mx = max(mx,vy);
sm += vy;
}
ans = max(ans,dp1[x]+mx);
dp0[x]=sm-dp1[x];
}
if (radj[x]!=-1) {
fdegL[radj[x]]--;
if (fdegL[radj[x]]==0) {
q1.push(radj[x]);
}
}
}
cout << ans << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |