이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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... |