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;
#define LCBorz ios_base::sync_with_stdio(false); cin.tie(0);
#define int long long
#define all(x) x.begin(), x.end()
#define endl '\n'
const int N=200005;
const int INF=1e9;
vector<int> adj[N];
vector dp(4,vector<int>(N,INF));
vector v(N,0);
void dfs(int k,int pa){
vector<int> dp0,dp1;
int t0=0,t1=0;
for(int j:adj[k]){
if(j==pa)continue;
dfs(j,k);
t0+=dp[0][j];
dp0.push_back({dp[1][j]-dp[0][j]});
t1+=dp[2][j];
dp1.push_back({dp[3][j]-dp[2][j]});
}
sort(all(dp0));
sort(all(dp1));
int now=v[k]*2;
dp[now][k]=min(dp[now][k],t0);
for(int j:dp0){
now^=2;
t0+=j;
dp[now][k]=min(dp[now][k],t0);
}
now=(v[k]^1)*2+1;
dp[now][k]=min(dp[now][k],t1+1);
for(int j:dp1){
now^=2;
t1+=j;
dp[now][k]=min(dp[now][k],t1+1);
}
}
// change to 0
int32_t main() {
LCBorz;
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);
}
for(int i=1;i<=n;i++){
cin>>v[i];
}
dfs(1,1);
int ans=min(dp[0][1],dp[1][1]);
if(ans==INF){
cout<<"impossible"<<endl;
}
else{
cout<<ans<<endl;
}
return 0;
}
# | 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... |