Submission #116151

#TimeUsernameProblemLanguageResultExecution timeMemory
116151user202729Mousetrap (CEOI17_mousetrap)C++17
45 / 100
2575 ms86056 KiB
// https://oj.uz/problem/view/CEOI17_mousetrap
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
#include<functional>
#include<cassert>

int nn,trap,mouse;
std::vector<std::vector<int>> ad;

std::vector<int> par; // with root = trap
std::vector<int> nrock; // num of rock to put if mouse is trapped at [?]
// of course the mouse can only be trapped at nodes with <= 1 child (rooted somewhere)
void dfs1(int x){
	int const px=par[x];
	nrock[x]=nrock[px]+ad[x].size()-2;
	for(int child:ad[x])if(child!=px){
		par[child]=x;
		dfs1(child);
	}
}

std::vector<int> d1; // dist(?, line(trap, mouse))

std::vector<int> cost; // total cost if mouse is trapped at [?] = nrock + d1

int thr;
bool dfs3(int x,int par){ // is it possible to force mouse to be trapped at a node with cost <= thr ...
	// when start at x?
	int nchild=ad[x].size()-(par>=0);
	if(nchild==0)return cost[x]<=thr;
	if(nchild==1){
		if(cost[x]<=thr)return true;
		return false; // ???
	}
	int n_impos=0;
	for(int child:ad[x])if(child!=par){
		n_impos+=!dfs3(child,x);
	}
	return n_impos<=1;
}

int main(){
	std::ios::sync_with_stdio(false);std::cin.tie(nullptr);
	std::cin>>nn>>trap>>mouse;--trap;--mouse;
	ad.resize(nn);
	for(int u,v,_=nn-1;_--;){
		std::cin>>u>>v;--u;--v;
		ad[u].push_back(v);
		ad[v].push_back(u);
	}
	nrock.resize(nn);nrock[trap]=1;
	par.resize(nn);par[trap]=-1;
	for(int x:ad[trap]){
		par[x]=trap;
		dfs1(x);
	}

	d1.resize(nn,-1);
	std::queue<int> q;
	for(int x=mouse;x>=0;x=par[x]){
		q.push(x);
		d1[x]=0;
	}
	while(!q.empty()){
		int const x=q.front();q.pop();
		int const newd=d1[x]+1;assert(newd>0);
		for(int y:ad[x])if(d1[y]<0){
			d1[y]=newd;
			q.push(y);
		}
	}

	cost.resize(nn);
	std::transform(begin(nrock),end(nrock),begin(d1),begin(cost),std::plus<int>{});

	thr=nn;
	for(int r=1<<29;r;r>>=1){
		if(thr-r<0)continue;
		thr-=r;
		if(!dfs3(mouse,-1))
			thr+=r;
	}
	std::cout<<thr<<'\n';
	return 0;
}

/*
10 1 4  
1 2     
2 3     
2 4     
3 9     
3 5     
4 7     
4 6     
6 8     
7 10    
*/
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...