Submission #1357410

#TimeUsernameProblemLanguageResultExecution timeMemory
1357410weedywelonThe Xana coup (BOI21_xanadu)C++20
0 / 100
32 ms22240 KiB
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <limits.h>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <deque>
#include <map>
#include <chrono>
#include <random>
#include <bitset>
#include <tuple>
#include <cassert>
#define SZ(x) (LL)(x.size())
#define FR(i,a,b) for(LL i=(a);i<(b);++i)
#define FOR(i,n) FR(i,0,n)
#define FAST ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define A first
#define B second
#define mp(a,b) make_pair(a,b)
typedef long long LL;
typedef long double LD;
typedef unsigned long long ULL;
typedef unsigned __int128 U128;
typedef __int128 I128;
typedef std::pair<int,int> PII;
typedef std::pair<LL,LL> PLL;
typedef std::pair<LD,LD> PLD;
using namespace std;

const LL MAXN=1e5+5;
vector<LL> adj[MAXN];
LL dp[MAXN][4];
LL b[MAXN];

void dfs(LL u, LL par){
	LL sum0=0, sum1=0;
	for (LL v:adj[u]){
		if (v==par) continue;
		dfs(v,u);
		sum0+=dp[v][0];
		sum1+=dp[v][1];
	}
	
	//case 1: dont toggle u
	vector<LL> tmp; 
	for (LL v:adj[u]) tmp.push_back(dp[v][2]-dp[v][0]);
	sort(tmp.begin(),tmp.end());
	
	LL cur=0;
	dp[u][b[u]]=sum0;
	FOR(i,SZ(tmp)){
		if (tmp[i]>=0) break;
		cur+=tmp[i];
		if ((i+1)%2==b[u]) dp[u][0]=sum0+cur; //weve taken the same parity of b[u], bulb is now off
		else dp[u][1]=sum0+cur;
	}
	
	//case 2: toggle u
	tmp.clear();
	for (LL v:adj[u]) tmp.push_back(dp[v][3]-dp[v][1]);
	sort(tmp.begin(),tmp.end());
	
	sum1++;
	cur=0;
	dp[u][(b[u]+1)%2+2]=sum1;
	FOR(i,SZ(tmp)){
		if (tmp[i]>=0) break;
		cur+=tmp[i];
		if (i%2==b[u]) dp[u][2]=sum1+cur; //weve taken opp parity of b[u], bulb is now off
		else dp[u][3]=sum1+cur;
	}
}

signed main(){
	FAST;
	LL n; cin>>n;
	FOR(i,n-1){
		LL u,v; cin>>u>>v;
		adj[u].push_back(v);
		adj[v].push_back(u);
	}
	FR(i,1,n+1) cin>>b[i];
	
	FR(i,1,n+1) FOR(j,4) dp[i][j]=1e18;
	dfs(1,-1);
	
	/*FR(i,1,n+1){
		FOR(j,4) cout<<dp[i][j]<<" ";
		cout<<"\n";
	}*/
	LL ans=min(dp[1][0], dp[1][2]);
	if (ans>=1e18) cout<<"impossible";
	else cout<<ans;
	return 0;
}
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...