1. 程式人生 > >LCA【模板】

LCA【模板】

fat sample oid class () pac void 100% https

題目描述

如題,給定一棵有根多叉樹,請求出指定兩個點直接最近的公共祖先。

輸入輸出格式

輸入格式:

第一行包含三個正整數N、M、S,分別表示樹的結點個數、詢問的個數和樹根結點的序號。

接下來N-1行每行包含兩個正整數x、y,表示x結點和y結點之間有一條直接連接的邊(數據保證可以構成樹)。

接下來M行每行包含兩個正整數a、b,表示詢問a結點和b結點的最近公共祖先。

輸出格式:

輸出包含M行,每行包含一個正整數,依次為每一個詢問的結果。

輸入輸出樣例

輸入樣例
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
輸出樣例
4
4
1
4
4

說明

時空限制:1000ms,128M

數據規模:

對於30%的數據:N<=10,M<=10

對於70%的數據:N<=10000,M<=10000

對於100%的數據:N<=500000,M<=500000

樣例說明:

該樹結構如下:

技術分享圖片

第一次詢問:2、4的最近公共祖先,故為4。

第二次詢問:3、2的最近公共祖先,故為4。

第三次詢問:3、5的最近公共祖先,故為1。

第四次詢問:1、2的最近公共祖先,故為4。

第五次詢問:4、5的最近公共祖先,故為4。

故輸出依次為4、4、1、4、4。


std

#include<cstdio>
#include<cstring>
#include
<algorithm> using namespace std; const int MX=5000001; struct Edge{ int from,to,val,next; }edge[MX]; int first[MX],cnt,n,q,s; void addedge(int a,int b){ edge[++cnt].from = a ; edge[cnt].to = b; edge[cnt].next = first[a]; first[a] = cnt; } bool vis[MX]; int father[MX][22],dep[MX];
void dfs(int x) { vis[x] = true; for(int i = 1 ; i <= 20 ; i ++){ if(dep[x] < (1<<i))break;//1<<i == 2^i; father[x][i] = father[ father[x][i-1] ][i-1]; } for(int i = first[x] ; i ; i = edge[i].next){ int to = edge[i].to; if(vis[to])continue; else { father[to][0] = x; dep[to] = dep[x] + 1; dfs(to); } } } int LCA(int x, int y) { if(dep[x] < dep[y])swap(x,y); int t = dep[x] - dep[y]; for(int i = 0 ; i <= 20 ; i++) if((1<<i)&t) x = father[x][i]; if(x == y )return x; for(int i = 20 ; i >= 0 ; i--){ if(father[x][i] == father[y][i])continue; x = father[x][i]; y = father[y][i]; } return father[x][0]; } int main() { scanf("%d%d%d",&n,&q,&s); for(int i = 1 ; i <= n-1 ; ++i){ int x,y,val; scanf("%d%d",&x,&y); addedge(x,y); addedge(y,x); } dfs(s); for(int i = 1 ; i <= q ; i++){ int x,y; scanf("%d %d",&x,&y); printf("%d\n",LCA(x,y)); } return 0; }

LCA【模板】