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;
vector <vector <int>> adj;
const int maxn = 1e5 + 1;
int dp[maxn][2][2];
bool ready[maxn][2][2];
int state[maxn];
int solve(int s, int p, bool pressed_parent, bool pressed_now) {
int cur_color = (state[s] + pressed_parent + pressed_now) % 2;
int sz = adj[s].size();
if (s != p)
sz--;
if (sz == 0 && s != p) {
if (cur_color == 0)
return 0;
return 1e9;
}
if (ready[s][pressed_parent][pressed_now])
return dp[s][pressed_parent][pressed_now];
int best = 1e9;
for (int i = 0; i < (1 << sz); i++) {
int tp = 0;
for (int j = 0, cnt = 0; cnt < sz; j++) {
if (adj[s][j] == p)
continue;
bool y = i & (1 << cnt);
tp += solve(adj[s][j], s, pressed_now, y);
if (tp >= 1e9)
break;
cnt++;
}
tp += __builtin_popcount(i);
if ((__builtin_popcount(i) + cur_color) % 2 == 0)
best = min(best, tp);
}
ready[s][pressed_parent][pressed_now] = true;
dp[s][pressed_parent][pressed_now] = best;
return best;
}
int main() {
int n;
cin >> n;
adj.resize(n+1);
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 >> state[i];
int res = solve(1, 1, 0, 0);
int res2 = solve(1, 1, 0, 1) + 1;
if (min(res, res2) == 1e9)
cout << "impossible\n";
else
cout << min(res, res2) << '\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... |