이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
long long dp[100001][2][2];
vector<int> adj[100001];
long long arr[100001];
//0 i make myself not toggole , 1 i make myself toggole
//0 i am not toggole , i am toggole
void solve(int i,int pr){
for(auto j:adj[i]){
if(j==pr)continue;
solve(j,i);
}
//0 0
long long check = 0 , sum =0 , mi = 1e9;
for(auto j:adj[i]){
if(j==pr)continue;
if(dp[j][0][arr[j]]<dp[j][1][arr[j]]){
sum+=dp[j][0][arr[j]];
check+=0;
}else{
sum+=dp[j][1][arr[j]];
check+=1;
}
mi = min(mi,abs(dp[j][0][arr[j]]-dp[j][1][arr[j]]));
}
if((check%2)){
sum+=mi;
}
dp[i][0][0] = sum;
//0 1
check = 0 , sum =0 , mi = 1e9;
for(auto j:adj[i]){
if(j==pr)continue;
if(dp[j][0][arr[j]]<dp[j][1][arr[j]]){
sum+=dp[j][0][arr[j]];
check+=0;
}else{
sum+=dp[j][1][arr[j]];
check+=1;
}
mi = min(mi,abs(dp[j][0][arr[j]]-dp[j][1][arr[j]]));
}
if(!(check%2)){
sum+=mi;
}
dp[i][0][1] = sum;
//1 0
check = 1 , sum =0 , mi = 1e9;
for(auto j:adj[i]){
if(j==pr)continue;
if(dp[j][0][!arr[j]]<dp[j][1][!arr[j]]){
sum+=dp[j][0][!arr[j]];
check+=0;
}else{
sum+=dp[j][1][!arr[j]];
check+=1;
}
mi = min(mi,abs(dp[j][0][!arr[j]]-dp[j][1][!arr[j]]));
}
if((check%2)){
sum+=mi;
}
dp[i][1][0] = sum+1;
//1 1
check = 1 , sum =0 , mi = 1e9;
for(auto j:adj[i]){
if(j==pr)continue;
if(dp[j][0][!arr[j]]<dp[j][1][!arr[j]]){
sum+=dp[j][0][!arr[j]];
check+=0;
}else{
sum+=dp[j][1][!arr[j]];
check+=1;
}
mi = min(mi,abs(dp[j][0][!arr[j]]-dp[j][1][!arr[j]]));
}
if(!(check%2)){
sum+=mi;
}
dp[i][1][1] = sum+1;
}
int main(){
int n;
cin>>n;
for(int i = 0;i<n-1;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>>arr[i];
solve(1,0);
long long val = min(dp[1][0][arr[1]],dp[1][1][arr[1]]);
if(val>=1e9)cout<<"impossible"<<endl;
else cout<<val<<endl;
}
# | 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... |