#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvl = vector<vll>;
using pll = pair<ll,ll>;
using vpl = vector<pll>;
using vvp = vector<vpl>;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(),v.end()
vvl g, dp;
vll st;
ll calc(vll& up, bool x){
ll ans = 0;
if(!x){
for(ll i = 1; i < up.size(); i+=2){
ans += min<ll>(0, up[i]+up[i-1]);
}
}
else{
if(up.empty())return 1e9;
ans+=up[0];
for(ll i = 2; i < up.size(); i+=2){
ans += min<ll>(0, up[i]+up[i-1]);
}
}
return ans;
}
void dfs(ll cur, ll par){
vll up0, up1;
for(ll i:g[cur]){
if(i==par)continue;
dfs(i, cur);
dp[cur][0]+=dp[i][0];
dp[cur][2]+=dp[i][0];
up0.pb(dp[i][1] - dp[i][0]);
dp[cur][1]+=dp[i][2];
dp[cur][3]+=dp[i][2];
up1.pb(dp[i][3] - dp[i][2]);
}
sort(all(up0));
sort(all(up1));
dp[cur][1]++;
dp[cur][3]++;
if(st[cur]==0){
dp[cur][0] += calc(up0, 0);
dp[cur][2] += calc(up0, 1);
dp[cur][1] += calc(up1, 1);
dp[cur][3] += calc(up1, 0);
}
else{
dp[cur][0] += calc(up0, 1);
dp[cur][2] += calc(up0, 0);
dp[cur][1] += calc(up1, 0);
dp[cur][3] += calc(up1, 1);
}
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(NULL);
ll n, a, b;
cin >> n;
g = vvl(n);
dp = vvl(n, vll(4));
st=vll(n);
for(ll i = 0; i < n-1; ++i){
cin >> a >> b;
a--;b--;
g[a].pb(b);
g[b].pb(a);
}
for(ll i = 0; i < n; ++i)cin >> st[i];
dfs(0,0);
ll ans = min(dp[0][0], dp[0][1]);
if(ans > n)cout << "impossible";
else cout << ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |