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>
#define mp make_pair
#define pb emplace_back
#define fi first
#define se second
#define int long long
#define inf 1e9
#define ick cout<<"ickbmi32.9\n"
using namespace std;
int n;
vector<int> conn[100005];
int init[100005];
pair<pair<int, int>, pair<int, int>> dfs(int now, int fa) {
    /* vector stores: 
        fi.fi: off, not pressed
        fi.se: off, pressed
        se.fi: on, not pressed
        se.se: on, pressed
    */
    int tcon = 0, tconcnt = 0, alton = inf; 
    int tcoff = 0, tcoffcnt = 0, altoff = inf;
    pair<pair<int, int>, pair<int, int>> t;
    for(auto x: conn[now]) {
        if(x == fa) continue;
        t = dfs(x, now);
        if(t.fi.se < t.fi.fi) tcoffcnt++;
        if(t.se.se < t.se.fi) tconcnt++;
        tcoff += min(t.fi.se, t.fi.fi);
        tcon += min(t.se.se, t.se.fi);
        altoff = min(altoff, abs(t.fi.se - t.fi.fi));
        alton = min(alton, abs(t.se.se - t.se.fi));
    }
    pair<int, int> off;
    pair<int, int> on;
    if(tcoffcnt % 2 == 0) {
        off.fi = tcoff;
        on.fi = tcoff + altoff;
    }
    else {
        on.fi = tcoff;
        off.fi = tcoff + altoff;
    }
    if(tconcnt % 2 == 1) {
        off.se = tcon + 1;
        on.se = tcon + alton + 1;
    }
    else {
        on.se = tcon + 1;
        off.se = tcon + alton + 1;
    }
    if(init[now] == 1) return mp(on, off);
    else return mp(off, on);
}
signed main() {
    ios_base::sync_with_stdio(false); 
    cin.tie(0); cout.tie(0);
    cin >> n;
    int t, tt;
    for(int i = 1; i < n; i++) {
        cin >> t >> tt;
        conn[t].pb(tt);
        conn[tt].pb(t);
    }
    for(int i = 1; i <= n; i++) cin >> init[i];
    pair<pair<int, int>, pair<int, int>> ans = dfs(1, 1);
    if(min(ans.fi.fi, ans.fi.se) > n) cout << "impossible\n";
    else cout << min(ans.fi.fi, ans.fi.se) << '\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... |