Submission #1323873

#TimeUsernameProblemLanguageResultExecution timeMemory
1323873YSH2020The Xana coup (BOI21_xanadu)C++20
100 / 100
82 ms25308 KiB
#include <bits/stdc++.h>
using namespace std;

#define int long long
vector<int> adj[100005];

int dp[100005][2][2]; //end with this state instead, whether you are choosing this.
int state[100005];
void solve(int n, int p) {
    for (auto i:adj[n]) {
        if (i!=p) solve(i,n);
    }
    for (int i = 0; i < 2; i++) {
        //suppose the endstate is i.
        for (int j = 0; j < 2; j++) {
            //j=0 means notake, 
            //j=1 means take.
            //i^j is the state after considering all children.
            //dp[c][j][x] where sum of x mod2 is i^j. if notake
            //dp[c][j][x] where sum of x mod 2 is i^j if take.
            //we first consider taking all =0 first.
            vector<int> diff;
            int total=0;
            for (auto x:adj[n]) if (x!=p) {
                total += dp[x][j][0];
                diff.push_back(dp[x][j][1]-dp[x][j][0]);
            }
            sort(diff.begin(), diff.end());
            if (i^j^state[n]==1 && diff.size()==0) {dp[n][i][j]=2e9; continue;}
            else if (diff.size()==0) {dp[n][i][j]=total+j; continue;}
            int start=0;
            if (i^j^state[n]==1) {
                total += diff[0];
                start=1;
            }
            int ans=total;
            while(start < diff.size()-1){
                total += diff[start];
                total += diff[start+1];
                ans=min(ans,total);
                start+=2;
            }
            dp[n][i][j]=ans+j;
        }
    }
}


signed main() {
    int n; cin >> n;
    for (int i = 0; i < n-1; i++) {
        int a,b; cin >> a>> b;
        a--;b--;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    for (int i = 0; i < n; i++) cin >> state[i];
    solve(0,-1);
    int ans=min(dp[0][0][0], dp[0][0][1]);
    if (ans>2e6) cout << "impossible";
    else cout << ans;
}
#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...