이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#define MAXN 100007
using namespace std;
int n,a,b,c[MAXN];
vector<int> v[MAXN];
vector<int> sp[MAXN][2][2];
vector<bool> us[MAXN][2][2];
int dp[MAXN][2][2],ans;
bool li[MAXN][2][2];
int ff(int x,int p,int fx,int fp);
int ff2(int x,int p,int ost,int d,int id);
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n-1;i++){
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
for(int f=0;f<2;f++){
for(int k=0;k<2;k++){
sp[a][f][k].push_back(0); sp[b][f][k].push_back(0);
us[a][f][k].push_back(false); us[b][f][k].push_back(false);
}
}
}
for(int i=1;i<=n;i++){
cin>>c[i];
}
ans=min(ff(1,0,0,0),ff(1,0,1,0)+1);
if(ans>=1000000){
cout<<"impossible\n";
}else{
cout<<ans<<"\n";
}
return 0;
}
int ff(int x,int p,int fx,int fp){
if(v[x].size()==1 and p!=0){
if((c[x]^(fx^fp))==0)return 0;
else return 1000000;
}
if(li[x][fx][fp])return dp[x][fx][fp];
li[x][fx][fp]=true;
dp[x][fx][fp]=ff2(x,p,(c[x]^(fx^fp)),fx,v[x].size()-1);
return dp[x][fx][fp];
}
int ff2(int x,int p,int ost,int fp,int id){
if(id==-1 and ost==0)return 0;
else if(id==-1)return 1000000;
if(us[x][ost][fp][id])return sp[x][ost][fp][id];
us[x][ost][fp][id]=true;
if(v[x][id]==p)sp[x][ost][fp][id]=ff2(x,p,ost,fp,id-1);
else sp[x][ost][fp][id]=min( ff2(x,p,ost,fp,id-1)+ff(v[x][id],x,0,fp) , ff2(x,p,(ost^1),fp,id-1)+ff(v[x][id],x,1,fp)+1 );
return sp[x][ost][fp][id];
}
# | 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... |