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 pb push_back
using namespace std;
const int N = 1e5 + 1;
const int inf = 1e9;
bool turned[N];
vector <int> g[N];
int dp[N][2][2];
void dfs(int v, int p) {
for (int to : g[v]) {
if (to != p) {
dfs(to, v);
}
}
int sum = 0;
bool flip = 0;
dp[v][0][0] = inf;
dp[v][0][1] = inf;
dp[v][1][0] = inf;
dp[v][1][1] = inf;
for (int to : g[v]) {
if (to != p) {
if (dp[to][0][0] == inf && dp[to][0][1] == inf) {
sum = inf;
break;
}
if (dp[to][0][0] == inf) sum += dp[to][0][1], flip ^= 1;
if (dp[to][0][1] == inf) sum += dp[to][0][0];
}
}
dp[v][turned[v] ^ flip][0] = min(dp[v][turned[v] ^ flip][0], sum);
sum = 0;
flip = 1;
for (int to : g[v]) {
if (to != p) {
if (dp[to][1][0] == inf && dp[to][1][1] == inf) {
sum = inf;
break;
}
if (dp[to][1][0] == inf) sum += dp[to][1][1], flip ^= 1;
if (dp[to][1][1] == inf) sum += dp[to][1][0];
}
}
dp[v][turned[v] ^ flip][1] = min(dp[v][turned[v] ^ flip][1], sum + 1);
}
int main(){
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
g[u].pb(v);
g[v].pb(u);
}
for (int i = 1; i <= n; i++) {
cin >> turned[i];
}
dfs(1, 1);
int ans = min(dp[1][0][0], dp[1][0][1]);
if (ans == inf) cout << "impossible";
else cout << 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... |