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 <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <cmath>
#include <map>
#include <string>
#include <ios>
#include <iomanip>
#include <deque>
#include <queue>
#include <list>
#include <stack>
#define FASTIO ios_base::sync_with_stdio(0); cin.tie(NULL);
using ll = long long;
using namespace std;
vector<vector<ll>>gp;
vector<ll>v;
vector<vector<vector<ll>>>dp;
void dfs(ll u,ll p){
ll cnt=1e18,lox=1e18,ans=0,ans1=0;
for(ll& x:gp[u]){
if(x!=p){
dfs(x,u);
dp[u][0][0]+=min(dp[x][0][0],dp[x][1][0]);
dp[u][1][0]+=min(dp[x][1][1],dp[x][0][1]);
if(min(dp[x][0][0],dp[x][1][0])==dp[x][1][0]) ans++;
if(min(dp[x][0][1],dp[x][1][1])==dp[x][1][1]) ans1++;
cnt=min(cnt,abs(dp[x][0][0]-dp[x][1][0]));
lox=min(lox,abs(dp[x][1][1]-dp[x][0][1]));
}
}
if(gp[u].size()==1&&u!=0){
if(v[u]==0){
dp[u][0][0]=0;
dp[u][0][1]=1e17;
dp[u][1][0]=1e17;
dp[u][1][1]=1;
}
else{
dp[u][0][0]=1e17;
dp[u][0][1]=0;
dp[u][1][0]=1;
dp[u][1][1]=1e17;
}
}
else{
dp[u][0][1]=dp[u][0][0]+1;
dp[u][1][1]=dp[u][1][0]+1;
if((v[u]==1&&ans%2==0)||(v[u]==0&&ans%2==1)){
dp[u][0][0]+=cnt;
}
if((v[u]==1&&ans%2==1)||(v[u]==0&&ans%2==0)){
dp[u][0][1]+=cnt;
}
if((v[u]==1&&ans1%2==0)||(v[u]==0&&ans1%2==1)){
dp[u][1][1]+=lox;
}
if((v[u]==1&&ans1%2==1)||(v[u]==0&&ans1%2==0)){
dp[u][1][0]+=lox;
}
}
}
void solve(){
ll n; cin >> n;
v=vector<ll>(n);
gp=vector<vector<ll>>(n);
dp=vector<vector<vector<ll>>>(n,vector<vector<ll>>(2,vector<ll>(2)));
for(ll i=0;i<n-1;i++){
ll u,v; cin >> u >> v;
--u,--v;
gp[u].push_back(v);
gp[v].push_back(u);
}
for(ll i=0;i<n;i++){
cin >> v[i];
}
dfs(0,-1);
// cout<<dp[4][0][1]<<endl;
// cout<<dp[4][1][1]<<endl;
// cout<<dp[4][0][0]<<endl;
// cout<<dp[4][1][0]<<endl;
// cout<<dp[0][0][1]<<endl;
// cout<<dp[0][1][1]<<endl;
// cout<<dp[0][0][0]<<endl;
// cout<<dp[0][1][0]<<endl;
if(min({dp[0][0][0],dp[0][1][0]})>=n){
cout<<"impossible"<<endl;
}
else cout<<min({dp[0][0][0],dp[0][1][0]});
}
signed main() {
FASTIO
ll t=1;
// cin >> t;
while (t--) {
solve();
}
}
# | 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... |