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 int long long
const int MAXN = 1e5 + 25;
vector <int> adj[MAXN];
bool ok[MAXN];
int dp[MAXN][2][2], n;
int ans (int pos, int par, int x, int y) {
int &ret = dp[pos][x][y];
if (ret != -1) return ret;
if (adj[pos].size() == 1 && par != -1) {
if (ok[pos] ^ x ^ y) {
return ret = 1e9;
}
return ret = y;
}
int p[2] = {}; //subset which adds even parity
int q[2] = {}; //subset which adds odd parity
int cnt = 0;
for (auto i : adj[pos]) {
if (i == par) continue;
cnt++;
if (cnt == 1) {
q[0] = ans(i, pos, y, 1);
p[0] = ans(i, pos, y, 0);
continue;
}
p[1] = min(ans(i, pos, y, 0) + p[0], ans(i, pos, y, 1) + q[0]);
q[1] = min(ans(i, pos, y, 0) + q[0], ans(i, pos, y, 1) + p[0]);
q[0] = q[1]; p[0] = p[1];
}
bool i = ok[pos] ^ x ^ y;
if (i) return ret = y + q[0];
else return ret = y + p[0];
}
signed main () {
memset(dp, -1, sizeof(dp));
cin >> n;
for (int i = 1; i < n; 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 >> ok[i];
int x = min(ans(1, -1, 0, 0), ans(1, -1, 0, 1));
if (x <= n) {
cout << x << '\n';
} else {
cout << "impossible\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... |