RMQ & LCA 专题
poj 1330 裸LCA
#define M 10005 int parent[M]; // 根节点 int Find(int i){ int j; for(j = i; j != parent[j]; j = parent[j]); while(i != j){ int temp = parent[i]; parent[i] = j; i = temp; } return j; } void Union(int a, int b){ int x = Find(a), y = Find(b); if(x == y) return; parent[y]=x; } void Make(int SIZE){ for(int i=0; i<=SIZE; i++) { parent[i]=i; } } struct edge{ int v,next; }E[M]; int head[M], p; int vis[M], rt; int n, a, b, ans; void ins(int u, int v) { E[p].v = v; E[p].next = head[u]; head[u] = p++; } bool f; void dfs(int u){ if(f) return ; vis[u] = 1; for(int i = head[u]; i != -1; i = E[i].next){ int v = E[i].v; dfs(v); Union(u, v); } if(u==a && vis[b]){ ans = Find(b); f = true; return; }else if(u==b && vis[a]){ ans = Find(a); f = true; return; } } int main(){ #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); #endif int T; scanf("%d", &T); while(T--){ memset(head, -1, sizeof head); memset(vis, 0, sizeof vis); p = 0; scanf("%d", &n); FOR(i, 1, n){ scanf("%d%d", &a, &b); ins(a, b); vis[b] = 1;//b不是根 } FOE(i, 1, n) if(vis[i]==0) {rt = i; break;} //确定根 scanf("%d%d", &a, &b); f = false; memset(vis, 0, sizeof vis); Make(n); dfs(rt); printf("%d\n", ans); } return 0; }