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;
typedef int64_t ll;
const int N = 100'005;
int n, dp[N][2][2], a[N];
vector<int> adj[N];
int dfs(int i, int par, int parf, int curf) {
if (~dp[i][parf][curf]) {
return dp[i][parf][curf];
}
vector<int> newadj;
for (auto nxt : adj[i]) {
if (nxt == par) continue;
newadj.push_back(nxt);
dfs(nxt, i, curf, 0);
dfs(nxt, i, curf, 1);
}
adj[i] = newadj;
int m = adj[i].size();
int dp2[m + 1][2]{};
memset(dp2, '?', sizeof dp2);
dp2[m][a[i] ^ parf ^ curf] = curf;
for (int j = m - 1; j >= 0; j--) {
for (int k = 0; k < 2; k++) {
dp2[j][k] = min(dp2[j + 1][k ^ 1] + dp[adj[i][j]][curf][1], dp2[j + 1][k] + dp[adj[i][j]][curf][0]);
dp2[j][k] = min(dp2[j][k], int(1e9));
}
}
return dp[i][parf][curf] = dp2[0][0];
}
int main() {
ios_base::sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
memset(dp, -1, sizeof dp);
int ans1 = dfs(1, 0, 0, 0);
int ans2 = dfs(1, 0, 0, 1);
if (min(ans1, ans2) >= int(1e9)) {
cout << "impossible\n";
} else {
cout << min(ans1, ans2) << '\n';
}
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... |