整理的算法模板:ACM算法模板總結(分類詳細版)
給定一棵包含 nn 個節點的有根無向樹,節點編號互不相同,但不一定是 1∼n1∼n。
有 mm 個詢問,每個詢問給出了一對節點的編號 xx 和 yy,詢問 xx 與 yy 的祖孫關係。
輸入格式
輸入第一行包括一個整數 表示節點個數;
接下來 nn 行每行一對整數 aa 和 bb,表示 aa 和 bb 之間有一條無向邊。如果 bb 是 −1−1,那麼 aa 就是樹的根;
第 n+2n+2 行是一個整數 mm 表示詢問個數;
接下來 mm 行,每行兩個不同的正整數 xx 和 yy,表示一個詢問。
輸出格式
對於每一個詢問,若 xx 是 yy 的祖先則輸出 11,若 yy 是 xx 的祖先則輸出 22,否則輸出 00。
數據範圍
1≤n,m≤4×1041≤n,m≤4×104,
1≤每個節點的編號≤4×1041≤每個節點的編號≤4×104
輸入樣例:
10
234 -1
12 234
13 234
14 234
15 234
16 234
17 234
18 234
19 234
233 19
5
234 233
233 12
233 13
233 15
233 19
輸出樣例:
1
0
0
0
2
每日靠寫寫模板題勉強度日。。。。。;裸的最近最近公共最先;
(我自己給自己說一遍步驟吧,反正也沒人看)
depth[]代表一個數的深度 fa[i][j]代表從節點i往上跳躍2的j次方個點得到的節點座標;
哨兵:如果從i開始跳2^ j 個節點跳過了根節點,那麼fa[i,j]=0,depth[0]=0;
步驟:
- 先將兩個點跳到同一層(原理爲數的二進制分解)
- 讓兩個點同時往上跳,一直跳到他們最近公共祖先的下一層
時間複雜度:bfs處理每個點的深度O(nlogn); 查詢 O(logn);
板子:
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+7,M=N*2;
int h[N],ne[M],e[M],idx;
int depth[N],fa[N][30];
int qq[N];
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void bfs(int root)
{
memset(depth,0x3f,sizeof depth);
queue<int> q;
q.push(root);
depth[0]=0,depth[root]=1;
while(q.size())
{
int t=q.front();
q.pop();
for(int i=h[t];~i;i=ne[i])
{
int j=e[i];
if(depth[j]>depth[t]+1)
{
depth[j]=depth[t]+1;
fa[j][0]=t;
q.push(j);
for(int k=1;k<30;k++)
fa[j][k]=fa[fa[j][k-1]][k-1];
}
}
}
}
int lca(int a,int b)
{
if(depth[a]<depth[b]) swap(a,b);
for(int k=19;k>=0;k--)
if(depth[fa[a][k]]>=depth[b])
a=fa[a][k];
if(a==b) return a;
for(int k=29;k>=0;k--)
{
if(fa[a][k]!=fa[b][k])
{
a=fa[a][k];
b=fa[b][k];
}
}
return fa[a][0];
}
int main()
{
memset(h,-1,sizeof h);
int u,v,n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<n;i++)
{
scanf("%d %d",&u,&v);//存圖
add(u,v);
add(v,u);
}
bfs(1);
while(m--)
{
int q;
cin >>q;
for(int i=0;i<q;i++) cin >>qq[i];
int flag=1;
int maxx=depth[qq[0]],res=0;
for(int i=1;i<q;i++) if(depth[qq[i]]>maxx) maxx=depth[qq[i]],res=i;
for(int i=0;i<q;i++)
{
int fa=lca(qq[i],qq[res]);
if(abs(depth[fa]-depth[qq[i]])>1)
{
flag=0;
break;
}
}
if(flag) cout <<"YES"<<endl;
else cout <<"NO"<<endl;
}
return 0;
}