Submission #1324005

#TimeUsernameProblemLanguageResultExecution timeMemory
1324005maxiedThe Xana coup (BOI21_xanadu)C++20
0 / 100
57 ms31184 KiB
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	int n;
	cin >> n;
	vector<vector<int>> adj(n);
	for (int i = 0, u,v ; i < n - 1; i++){
		cin >> u >> v;
		u--, v--;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}
	vector<int> t(n);
	for (int i = 0; i < n; i++){
		cin >> t[i];
	}
	vector<vector<vector<i64>>> dp(2, vector<vector<i64>>(2, vector<i64>(n, 3e5)));
	auto dfs = [&](auto &&me, int u, int p) -> void{
		for (int v : adj[u]){
			if (v == p){
				continue;
			}
			me(me, v, u);
		}
		for (int tg = 0; tg < 2; tg++){
			for (int fl = 0; fl < 2; fl++){
				int uneq = t[u] ^ tg ^ fl;
				vector<pair<i64,i64>> unsure;
				i64 tot = 0;
				for (int v : adj[u]){
					if (v == p){
						continue;
					}
					tot += dp[fl][0][v];
					unsure.push_back({dp[fl][0][v], dp[fl][1][v]});
				}
				if (unsure.empty()){
					if (uneq){
						dp[tg][fl][u] = 3e5;
					}
					else{
						dp[tg][fl][u] = tot + fl;
					}
				}
				else{
					vector<i64> ch;
					for (auto &[a, b] : unsure){
						ch.push_back(b - a);
					}
					sort(ch.begin(), ch.end());
					i64 ans = 3e5;
					int take = 0;
					while (take < uneq){
						tot += ch[take];
						take++;
					}
					ans = min(ans, tot);
					while (take + 1 < unsure.size()){
						tot += ch[take] + ch[take + 1];
						take += 2;
						ans = min(ans, tot);
					}
					dp[tg][fl][u] = ans + fl;
				}
			}
		}
	};
	dfs(dfs, 0, 0);
	i64 res = min(dp[0][0][0], dp[0][1][0]);
	if (res >= 2e6){
		cout << "impossible";
	}
	else{
		cout << res;
	}
}
#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...