제출 #672847

#제출 시각아이디문제언어결과실행 시간메모리
672847ParsaSThe Xana coup (BOI21_xanadu)C++17
100 / 100
74 ms25420 KiB
// In the name of God
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define fi first
#define se second
#define mp make_pair
typedef long long ll;
const int N = 2e5 + 5;
int n;
vector<int> adj[N];
ll dp[N][2][2];
bool a[N];

void dfs(int v, int p) {
    ll ans[2] = {0, 0}, cnt[2] = {0, 0};
    ll del[2] = {n * 10LL, n * 10LL};
    for (auto u : adj[v]) {
        if (u == p)
            continue;
        dfs(u, v);
        for (int i = 0; i < 2; i++) {
            ans[i] += min(dp[u][0][i], dp[u][1][i]);
            del[i] = min(del[i], (ll)abs(dp[u][0][i] - dp[u][1][i]));
            cnt[i] += dp[u][1][i] <= dp[u][0][i];
        }
    }
    if (adj[v].size() == 1) {
        for (int i = 0; i < 2; i++) {
            dp[v][i][a[v] ^ i] = i;
        }
        return;
    }
    dp[v][0][a[v]] = ans[0] + ((cnt[0] % 2) ? del[0] : 0LL);
    dp[v][0][a[v] ^ 1] = ans[0] + ((cnt[0] % 2) == 0 ? del[0] : 0LL);
    dp[v][1][a[v]] = ans[1] + ((cnt[1] % 2) == 0 ? del[1] : 0LL) + 1;
    dp[v][1][a[v] ^ 1] = ans[1] + ((cnt[1] % 2) ? del[1] : 0LL) + 1;
}

void solve() {
    cin >> n;
    for (int i = 0; i< n - 1; i++) {
        int v, u; cin >> v >> u;
        adj[v].pb(u), adj[u].pb(v);
    }
    int rt = 1;

    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        if (adj[i].size() > 1)
            rt = i;
    }
    for (int i = 0; i <= n; i++)
        for (int j = 0; j < 2; j++)
            for (int k = 0; k < 2; k++)
                dp[i][j][k] = n * 10;
    dfs(rt, 0);
    ll ans = min(dp[rt][0][0], dp[rt][1][0]);
    if (ans <= n)
        cout << ans << endl;
    else
        cout << "impossible" << endl;
}

int32_t main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    solve();
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...