1. 程式人生 > >洛谷 P3379 【模板】最近公共祖先(LCA) 如題

洛谷 P3379 【模板】最近公共祖先(LCA) 如題

content 接下來 mit 裏的 mar lap define 第一次 樹根

P3379 【模板】最近公共祖先(LCA)

  • 時空限制1s / 512MB

題目描述

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

輸入輸出格式

輸入格式:

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

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

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

輸出格式:

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

輸入輸出樣例

輸入樣例#1:
5 5 4
3 1
2 4
5 1
1 4
2 4
3 2
3 5
1 2
4 5
輸出樣例#1:
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。

----------------------------------------------------------------------------------------------------------------

註意題目中的邊是無向的,所以要建雙向,所以邊數應為m*2,需要開兩倍數組(我沒註意只開了一倍就蠢蠢地submit結果。。。)

這裏的倍增+LCA

把表示冪的一維放到前面

就是把小的一維放到前面

會對內存友好

聽說就會快很多

存板子:

技術分享
 1 #include<stdio.h>
 2
#include<string.h> 3 #include<iostream> 4 #define maxn 500010 5 using namespace std; 6 struct node{ 7 int to,next; 8 }; 9 node e[maxn<<1]; 10 int read(); 11 int n,m,s,pre[maxn],cnt,len[maxn],p[23][maxn]; 12 bool po[maxn]; 13 int lca(int,int); 14 void dfs(int); 15 void ycl(); 16 void build(int,int); 17 int main(){ 18 memset(po,0,sizeof(po)); 19 n=read();m=read();s=read(); 20 cnt=0; 21 for(int i=1;i<n;i++){ 22 int x=read(),y=read(); 23 build(x,y); 24 } 25 len[s]=1;po[s]=1; 26 dfs(s); 27 ycl(); 28 for(int i=1;i<=m;i++){ 29 int x=read(),y=read(); 30 printf("%d\n",lca(x,y)); 31 } 32 return 0; 33 } 34 int lca(int x,int y){ 35 if(len[x]>len[y]) swap(x,y); 36 int k=len[y]-len[x]; 37 for(int j=0;(1<<j)<=k;j++) 38 if((1<<j)&k) y=p[j][y]; 39 if(x==y) return x; 40 for(int j=21;j>=0;j--) 41 if(p[j][x]!=p[j][y]){ 42 x=p[j][x]; 43 y=p[j][y]; 44 } 45 return p[0][y]; 46 } 47 void dfs(int x){ 48 for(int i=pre[x];i;i=e[i].next){ 49 int to=e[i].to; 50 if(!po[to]){ 51 po[to]=1; 52 len[to]=len[x]+1; 53 p[0][to]=x; 54 dfs(to); 55 } 56 } 57 } 58 void ycl(){ 59 for(int j=1;(1<<j)<=n;j++) 60 for(int i=1;i<=n;i++) 61 p[j][i]=p[j-1][p[j-1][i]]; 62 } 63 void build(int x,int y){ 64 e[++cnt].to=y;e[cnt].next=pre[x];pre[x]=cnt; 65 e[++cnt].to=x;e[cnt].next=pre[y];pre[y]=cnt; 66 } 67 int read(){ 68 int ans=0,f=1;char c=getchar(); 69 while(0>c||c>9){if(c==-)f=-1;c=getchar();} 70 while(0<=c&&c<=9)ans=ans*10+c-48,c=getchar();return ans*f; 71 }
倍增+LCA

洛谷 P3379 【模板】最近公共祖先(LCA) 如題