1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| #include <bits/stdc++.h> #define mp make_pair #define rep(x,y,z) for (int x=(y);(x)<=(z);(x)++) #define per(x,y,z) for (int x=(y);(x)>=(z);(x)--) #define lowbit(x) ((x)&(-(x))) #define cls(x) memset(x,0,sizeof(x)) #ifdef DEBUG #define debugdo(X) X #define debugndo(X) #define debugout(X) cout<<(#X)<<"="<<(X)<<endl #else #define debugdo(X) #define debugndo(X) X #define debugout(X) #endif using namespace std; mt19937 rnd(19260817); const int inf=0x3f3f3f3f; typedef long long LL; typedef pair<int,int> pii;
template<typename T> inline void read(T &x){char ch;x=0;bool flag=false;ch=getchar();while (ch>'9'||ch<'0') {if (ch=='-') flag=true;ch=getchar();}while ((ch<='9'&&ch>='0')){x=x*10+ch-'0';ch=getchar();}if (flag) x*=-1;} template<typename T,typename U> inline void read(T &x,U &y){read(x);read(y);} template<typename T,typename U,typename V> inline void read(T &x,U &y,V &z){read(x);read(y);read(z);}
const int maxn=555555; #define log2(x) (31-__builtin_clz(x)) const int logn=log2(maxn); template <typename T> struct ST_Table { T a[maxn][logn+1]; T f(T x,T y) { return max(x,y); } void init(int n) { rep(i,1,logn) for (T j=1;j+(1<<i)-1<=n;j++) a[j][i]=f(a[j][i-1],a[j+(1<<(i-1))][i-1]); } T query(int l,int r) { int s=log2(r-l+1); return f(a[l][s],a[r-(1<<s)+1][s]); } ST_Table<T>(){} }; ST_Table<int> pp,bb;
vector<int> g[maxn]; int dep[maxn],fa[maxn],n,s,t; bool dfs(int u,int p) { bool in_main_chain=(u==t); fa[u]=p; dep[u]=0; for (auto v:g[u]) { if (v==p) continue; if (dfs(v,u)) in_main_chain=true; else dep[u]=max(dep[u],dep[v]+1); } return in_main_chain; } int main() { read(n,s,t); rep(i,1,n-1) { int u,v; read(u,v); g[u].push_back(v); g[v].push_back(u); } dfs(s,0);
int tt=t; vector<int> main_chain; while (tt!=s) { main_chain.push_back(tt); tt=fa[tt]; } main_chain.push_back(s); main_chain.push_back(0); reverse(main_chain.begin(), main_chain.end());
int m=main_chain.size()-1; rep(i,1,m) pp.a[i][0]=dep[main_chain[i]]+i-1; per(i,m,1) bb.a[i][0]=dep[main_chain[i]]+(m-i); pp.init(m);bb.init(m);
vector<int> Rans; for (int l=1,r=m,i=1;l<=(m+1)/2||r>=(m+1)/2+1;i++) { if (i&1) { int u=main_chain[l],anss=dep[u]+l-1,anst=bb.query(l+1,r); if (l==r) anst=m-l; Rans.push_back(anss-anst); l++; } else { int u=main_chain[r],anss=pp.query(l,r-1),anst=dep[u]+(m-r); if (l==r) anss=r-1; Rans.push_back(anss-anst); r--; } } bool whose_turn=Rans.size()&1; reverse(Rans.begin(),Rans.end()); int ans=whose_turn?-inf:inf; for (auto to:Rans) { if (whose_turn) ans=max(ans,to); else ans=min(ans,to); whose_turn^=1; } cout<<ans<<endl; return 0; }
|