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;
using ll = long long;
#define MAXN (100005)
ll N;
vector<ll> v[MAXN];
ll dp[MAXN][2][2]; //index, final state, do operation on node x
bool initial[MAXN];
void dfs(ll x,ll p){
ll child = 0;
for(auto u : v[x]){
if(u != p){
dfs(u,x);
child++;
if(initial[x] == 0){
dp[x][0][0] += dp[u][0][0];
dp[x][0][1] += dp[u][1][1];
dp[x][1][0] += dp[u][0][1];
dp[x][1][1] += dp[u][1][0];
}else if(initial[x] == 1){
dp[x][0][0] += dp[u][0][1];
dp[x][0][1] += dp[u][1][0];
dp[x][1][0] += dp[u][0][0];
dp[x][1][1] += dp[u][1][1];
}
}
}
if(child == 0){ //base case (leaf nodes)
dp[x][initial[x]][0] = 0;
dp[x][!initial[x]][1] = 1;
}
}
int main() {
ios_base::sync_with_stdio(false);cin.tie(0);
cin>>N;
for(ll i = 0;i < N - 1;i++){
ll a,b;
cin>>a>>b;
a--, b--;
v[a].push_back(b);
v[b].push_back(a);
}
for(ll i = 0;i < N;i++){
cin>>initial[i];
}
for(ll i = 0;i < N;i++){
for(ll j = 0;j < 2;j++){
for(ll k = 0;k < 2;k++){
dp[i][j][k] = 1e9;
}
}
}
dfs(0,-1);
ll minimum = 1e9;
minimum = min({minimum,dp[0][0][0],dp[0][0][1]});
if(minimum >= 1e9){
cout<<"impossible"<<'\n';
}else{
cout<<minimum<<'\n';
}
}
# | 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... |