Input
Output
Sample Input
2 16 1 14 8 5 10 16 5 9 4 6 8 4 4 10 1 13 6 15 10 11 6 7 10 2 16 3 8 1 16 12 16 7 5 2 3 3 4 3 1 1 5 3 5
Sample Output
4 3
LCA模板题
//#include <bits/stdc++.h> #include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<queue> using namespace std; typedef long long ll; #define inf 2147483647 const ll INF = 0x3f3f3f3f3f3f3f3fll; #define ri register int template <class T> inline T min(T a, T b, T c) { return min(min(a, b), c); } template <class T> inline T max(T a, T b, T c) { return max(max(a, b), c); } template <class T> inline T min(T a, T b, T c, T d) { return min(min(a, b), min(c, d)); } template <class T> inline T max(T a, T b, T c, T d) { return max(max(a, b), max(c, d)); } #define pi acos(-1) #define me(x, y) memset(x, y, sizeof(x)); #define For(i, a, b) for (int i = a; i <= b; i++) #define FFor(i, a, b) for (int i = a; i >= b; i--) #define bug printf("***********\n"); #define mp make_pair #define pb push_back const int N = 1e5+5; const int M=200005; // name******************************* struct edge { int to,nxt,idx; } e[N<<1],e_[N]; int tot=1; int tot_=0; int fa[N]; int fst[N]; int fst_[N]; int rk[N]; int n,m,T; int acr[N]; int ins[N]; bool flag[N]; int ans[N]; // function****************************** void init() { tot=1; tot_=0; me(ins,0); For(i,1,n)fa[i]=i; me(rk,0); me(acr,0); me(fst,0); me(fst_,0); me(flag,0); } void add(int u,int v) { e[++tot].to=v; e[tot].nxt=fst[u]; fst[u]=tot; } void add_(int u,int v,int t) { e_[++tot_].to=v; e_[tot_].nxt=fst_[u]; e_[tot_].idx=t; fst_[u]=tot_; } int find(int x) { return x==fa[x]?x:fa[x]=find(fa[x]); } void uone(int a,int b) { int t1=find(a),t2=find(b); if(t1!=t2) { if(rk[t1]>rk[t2])fa[t2]=t1; else fa[t1]=t2; if(rk[t1]==rk[t2])rk[t2]++; } } void LCA(int u) { acr[u]=u; ins[u]=1; for(int p=fst[u]; p; p=e[p].nxt) { int v=e[p].to; if(ins[v])continue; LCA(v); uone(u,v); acr[find(u)]=u; } for(int p=fst_[u]; p; p=e_[p].nxt) { int v=e_[p].to; if(ins[v])ans[e_[p].idx]=acr[find(v)]; } } //*************************************** int main() { // ios::sync_with_stdio(0); // cin.tie(0); // freopen("test.txt", "r", stdin); // freopen("outout.txt","w",stdout); scanf("%d",&T); while(T--) { scanf("%d",&n); int u,v; init(); For(i,1,n-1) { scanf("%d%d",&u,&v); add(u,v); add(v,u); flag[v]=1; } For(i,1,1){ scanf("%d%d",&u,&v); add_(u,v,i); add_(v,u,i); } int pos; For(i,1,n) if(!flag[i]) { pos=i; break; } LCA(pos); For(i,1,1) printf("%d\n",ans[i]); } return 0; }
poj-1330 Nearest Common Ancestors
原文:https://www.cnblogs.com/planche/p/8904570.html