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 long long ll;
typedef double ld;
#define pb push_back
#define sz(x) int(x.size())
#define all(x) x.begin(),x.end()
#define F first
#define S second
const int N = 1e5+5;
int n, a[N];
vector<int> adj[N];
ll dp[N][2][2];
ll sol(int u, int pv, int nv, int par) {
ll &ret = dp[u][pv][nv];
if (~ret)return ret;
int cur = (a[u] ^ pv ^ nv);
if (!cur) {
ll mn = n+1;
bool c = 0;
ret = nv;
for (auto &v : adj[u]) {
if (v == par)continue;
ll f = sol(v, nv, 0, u), s = sol(v, nv, 1, u);
mn = min(mn, abs(f-s));
ret += min(f, s);
if (s < f)c ^= 1;
}
if (c)ret += mn;
return ret;
} else {
if (sz(adj[u]) == 1 && u)return ret = n+1;
ll mn = n+1;
bool c = 0;
ret = nv;
for (auto &v : adj[u]) {
if (v == par)continue;
ll f = sol(v, nv, 0, u), s = sol(v, nv, 1, u);
mn = min(mn, abs(f-s));
ret += min(f, s);
if (s < f)c ^= 1;
}
if (!c)ret += mn;
return ret;
}
}
int main () {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 0; i+1 < n; i++) {
int u, v;
cin >> u >> v;
--u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
for (int i = 0; i < n; i++) {
cin >> a[i];
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
dp[i][j][k] = -1;
}
}
}
ll x = min(sol(0, 0, 1, 0), sol(0, 0, 0, 0));
if (x > n) {
cout << "impossible\n";
return 0;
}
cout << x << "\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... |