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>
#define int ll
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define rng(i,c,n) for(int i=c;i<n;i++)
#define fi first
#define se second
#define pb push_back
#define sz(a) (int)a.size()
#define vec(...) vector<__VA_ARGS__>
#define _3D2ZDxo ios::sync_with_stdio(0),cin.tie(0)
typedef long long ll;
using pii=pair<int,int>;
using vi=vector<int>;
void print(){cout<<'\n';}
template<class h,class...t>
void print(const h&v,const t&...u){cout<<v<<' ',print(u...);}
void chmin(int&a,int b){
a=min(a,b);
}
signed main(){
_3D2ZDxo;
int n;
cin>>n;
vec(vi) adj(n);
rep(i,n-1){
int u,v;
cin>>u>>v;
u-=1,v-=1;
adj[u].pb(v);
adj[v].pb(u);
}
vi a(n);
rep(i,n){
cin>>a[i];
}
rep(i,n){
a[i]^=1;
}
const int inf=1e9;
vec(vec(vi)) dp(n,vec(vi)(2,vi(2,inf)));
auto dfs=[&](auto self,int v,int par)->void{
for(auto u:adj[v]){
if(u==par) continue;
self(self,u,v);
}
vi fdp(2); // flip the root
fdp[a[v]^1]=1;
fdp[a[v]]=inf;
for(auto u:adj[v]){
if(u==par) continue;
vi nfdp(2,inf);
{
int t=0;
rep(t1,2){
rep(wit,2){
int nwit=wit^t1;
chmin(nfdp[nwit],fdp[wit]+dp[u][t][t1]);
}
}
}
fdp=nfdp;
}
vi gdp(2);
gdp[a[v]]=0;
gdp[a[v]^1]=inf;
for(auto u:adj[v]){
if(u==par) continue;
vi ngdp(2,inf);
{
int t=1;
rep(t1,2){
rep(wit,2){
int nwit=wit^t1;
chmin(ngdp[nwit],gdp[wit]+dp[u][t][t1]);
}
}
}
gdp=ngdp;
}
rep(t,2){
chmin(dp[v][t][1],fdp[t]);
chmin(dp[v][t][0],gdp[t]);
}
};
dfs(dfs,0,-1);
int ans=min(dp[0][1][0],dp[0][1][1]);
if(ans>=inf){
print("impossible");
}else{
print(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... |