Submission #528360

#TimeUsernameProblemLanguageResultExecution timeMemory
528360fatemetmhrThe Xana coup (BOI21_xanadu)C++17
100 / 100
96 ms38028 KiB
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int maxn5 = 1e6 + 10;

#define pb push_back

// dp[node][rangesh][khodesh zade shode ya na]

int dp[maxn5][2][2];
vector <int> adj[maxn5];
int ty[maxn5];

inline void dfs(int v, int par){

	dp[v][0][0] = dp[v][0][1] = dp[v][1][0] = dp[v][1][1] = maxn5;
	
	if(adj[v].size() == 1 && par != -1){
		dp[v][ty[v]][0] = 0;
		dp[v][ty[v]^1][1] = 1;
		return;
	}
	// dp[v][hame 0/1][tedad zoj ya fard]
	
	dp[v][0][0] = dp[v][1][0] = 0;
	
	for(auto u : adj[v]) if(u != par){
		dfs(u, v);
		int x = dp[v][0][0], y = dp[v][0][1];
		dp[v][0][0] = min({maxn5, x + dp[u][0][0], y + dp[u][0][1]});
		dp[v][0][1] = min({maxn5, x + dp[u][0][1], y + dp[u][0][0]});
		x = dp[v][1][0]; y = dp[v][1][1];
		dp[v][1][0] = min({maxn5, x + dp[u][1][0], y + dp[u][1][1]});
		dp[v][1][1] = min({maxn5, x + dp[u][1][1], y + dp[u][1][0]});
	}
	
	int a = dp[v][0][0], b = dp[v][0][1], c = dp[v][1][0], d = dp[v][1][1];
	dp[v][ty[v]][0] = a;
	dp[v][ty[v]][1] = d + 1;
	dp[v][ty[v]^1][0] = b;
	dp[v][ty[v]^1][1] = c + 1;
	//cout << v << ' ' << par << ' ' << dp[v][0][0] << ' ' << dp[v][0][1] << ' ' << dp[v][1][0] << ' '<< dp[v][1][1] << endl;
	return;
}

int main(){
	ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	
	int n; cin >> n;
	for(int i = 0; i < n - 1; i++){
		int a, b; cin >> a >> b;
		a--; b--;
		adj[a].pb(b);
		adj[b].pb(a);
	}
	
	for(int i = 0; i < n; i++)
		cin >> ty[i];
	
	dfs(0, -1);
	ll ans = min(dp[0][0][0], dp[0][0][1]);
	if(ans > n)
		cout <<  "impossible\n";
	else
		cout << ans << endl;
	
}













#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...