#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
const int MAXN=1e6;
int DP[MAXN+1];
vector<vector<int>> graph(MAXN+1);
vector<int> path;
bool in[MAXN+1]={false};
bool getpath(int u,int p,int t){
path.push_back(u);
if(u==t){
return true;
}
for(int v:graph[u]){
if(v!=p){
if(getpath(v,u,t)){
return true;
}
}
}
path.pop_back();
return false;
}
void DFS(int u,int p){
DP[u]=0;
vector<int> child;
for(int v:graph[u]){
if(v!=p&&!in[v]){
DFS(v,u);
child.push_back(DP[v]);
}
}
sort(child.begin(),child.end(),greater<int>());
DP[u]=child.size();
if(child.size()>=2){
DP[u]+=child[1];
}
}
int cost[MAXN+1];
signed main(){
//freopen("mousetrap.inp","r",stdin);
//freopen("mousetrap.out","w",stdout);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,t,root;
cin >> n >> t >> root;
for(int i=0;i<n-1;i++){
int u,v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
}
if(root==t){
cout << 0;
return 0;
}
getpath(root,-1,t);
for(int i=0;i<path.size();i++){
in[path[i]]=true;
}
int sum=0;
for(int i=path.size()-2;i>=0;i--){
int u=path[i],p=-1;
if(i>0){
p=path[i-1];
}
for(int v:graph[u]){
if(v!=p&&!in[v]){
sum++;
}
}
for(int v:graph[u]){
if(v!=p&&!in[v]){
DFS(v,-1);
cost[v]=DP[v]+sum;
}
}
}
int low=0,high=1e9;
low--,high++;
while(high-low>1){
int mid=((high-low)>>1)+low;
sum=0;
bool stop=true;
for(int i=0;i+1<path.size();i++){
int u=path[i],p=-1;
if(i>0){
p=path[i-1];
}
int cnt=0;
for(int v:graph[u]){
if(v!=p&&!in[v]&&cost[v]+sum>mid){
cnt++;
}
}
sum+=cnt;
if(sum>i+1){
stop=false;
break;
}
}
if(sum>mid){
stop=false;
}
if(!stop){
low=mid;
}
else{
high=mid;
}
}
cout << high;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |