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;
#define ll long long
#define int ll
#define ld long double
#define pii pair<int, int>
#define f first
#define s second
#define boost() cin.tie(0), cin.sync_with_stdio(0)
const int MN = 100005;
int n, u, v, p[MN], dp[MN][2][2]; //node, our state, do we flip parent
vector<int> a[MN];
void dfs(int cur, int par) {
int sum = 0, flip = 0, mn = 0x3f3f3f3f; //dont touch cur
for (int nxt : a[cur]) {
if (nxt == par) continue;
dfs(nxt, cur);
if (dp[nxt][0][0] < dp[nxt][0][1]) {
sum += dp[nxt][0][0];
mn = min(mn, dp[nxt][0][1] - dp[nxt][0][0]);
} else {
sum += dp[nxt][0][1];
flip ^= 1;
mn = min(mn, dp[nxt][0][0] - dp[nxt][0][1]);
}
}
dp[cur][p[cur] ^ flip][0] = sum;
dp[cur][p[cur] ^ flip ^ 1][0] = sum + mn;
sum = 0, flip = 0, mn = 0x3f3f3f3f; //flip cur
for (int nxt : a[cur]) {
if (nxt == par) continue;
if (dp[nxt][1][0] < dp[nxt][1][1]) {
sum += dp[nxt][1][0];
mn = min(mn, dp[nxt][1][1] - dp[nxt][1][0]);
} else {
sum += dp[nxt][1][1];
flip ^= 1;
mn = min(mn, dp[nxt][1][0] - dp[nxt][1][1]);
}
}
dp[cur][p[cur] ^ flip ^ 1][1] = sum + 1;
dp[cur][p[cur] ^ flip][1] = sum + mn + 1;
}
int32_t main() {
boost();
memset(dp, 0x3f, sizeof(dp));
cin >> n;
for (int i = 1; i < n; i++) {
cin >> u >> v;
a[u].push_back(v);
a[v].push_back(u);
}
for (int i = 1; i <= n; i++) cin >> p[i];
dfs(1, 0);
int ans = min(dp[1][0][0], dp[1][0][1]);
if (ans > n) printf("impossible\n");
else printf("%lld\n", ans);
return 0;
}
# | 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... |