poj 1330 Nearest Common Ancestors(倍增法)

本文介绍了一种高效算法——倍增法,用于解决寻找树中两节点的最近公共祖先(LCA)问题。通过预处理节点的深度及特定祖先信息,实现快速查询,适用于竞赛编程与实际工程项目。

Nearest Common Ancestors
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 14078 Accepted: 7510

Description

A rooted tree is a well-known data structure in computer science and engineering. An example is shown below:


In the figure, each node is labeled with an integer from {1, 2,...,16}. Node 8 is the root of the tree. Node x is an ancestor of node y if node x is in the path between the root and node y. For example, node 4 is an ancestor of node 16. Node 10 is also an ancestor of node 16. As a matter of fact, nodes 8, 4, 10, and 16 are the ancestors of node 16. Remember that a node is an ancestor of itself. Nodes 8, 4, 6, and 7 are the ancestors of node 7. A node x is called a common ancestor of two different nodes y and z if node x is an ancestor of node y and an ancestor of node z. Thus, nodes 8 and 4 are the common ancestors of nodes 16 and 7. A node x is called the nearest common ancestor of nodes y and z if x is a common ancestor of y and z and nearest to y and z among their common ancestors. Hence, the nearest common ancestor of nodes 16 and 7 is node 4. Node 4 is nearer to nodes 16 and 7 than node 8 is.

For other examples, the nearest common ancestor of nodes 2 and 3 is node 10, the nearest common ancestor of nodes 6 and 13 is node 8, and the nearest common ancestor of nodes 4 and 12 is node 4. In the last example, if y is an ancestor of z, then the nearest common ancestor of y and z is y.

Write a program that finds the nearest common ancestor of two distinct nodes in a tree.

Input

The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case starts with a line containing an integer N , the number of nodes in a tree, 2<=N<=10,000. The nodes are labeled with integers 1, 2,..., N. Each of the next N -1 lines contains a pair of integers that represent an edge --the first integer is the parent node of the second integer. Note that a tree with N nodes has exactly N - 1 edges. The last line of each test case contains two distinct integers whose nearest common ancestor is to be computed.

Output

Print exactly one line for each test case. The line should contain the integer that is the nearest common ancestor.

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

Source

Taejon 2002

在线算法 倍增法

每次询问O(logN)

d[i] 表示 i节点的深度, p[i,j] 表示 的 2^j 倍祖先

那么就有一个递推式子 p[i,j]=p[p[i,j-1],j-1]

这样子一个O(NlogN)的预处理求出每个节点的 2^k 的祖先

然后对于每一个询问的点对a, b的最近公共祖先就是:

先判断是否 d[a] > d[b] ,如果是的话就交换一下(保证 的深度小于 方便下面的操作)然后把调到与同深度同深度以后再把a, b 同时往上调(dec(j)) 调到有一个最小的满足p[a,j]!=p[b,j] (a b 是在不断更新的), 最后再把 a, b 往上调 (a=p[a,0], b=p[b,0]) 一个一个向上调直到a = b, 这时 a or b 就是他们的最近公共祖先

http://poj.org/problem?id=1330 

【分析】

倍增法求LCA的大体思路:

     首先确定深度d[i],表示i到根节点的距离或者说是深度。

     p[i,j]表示i向上的第2^j个祖先,则p[i,j+1]:=p[p[i,j],j];

     dfs求出d[i]和p[i,j]。

     如果求的是x和y的lca。那么如果x=y,lca=x or y;

     如果x和y的深度不同,则调整到同一深度,以便求lca。

     x和y的深度相同了,就开始向上走,如果两个点同时走了相同的步数,走到了一个点,那么这个点就是lca,自己想象一下,这是显然的事。两个点最早到达的相同点不是lca是什么= =

     结束。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define N 10010
#define M 20
int d[N],f[N][M];
vector<int>ch[N];
void dfs(int x){//求出所有结点深度
	d[x]=d[f[x][0]]+1;
	for(int i=1;i<M;i++)f[x][i]=f[f[x][i-1]][i-1];//倍增祖先
	for(int i=ch[x].size()-1;i>=0;i--)
		dfs(ch[x][i]);//遍历儿子
}
int lca(int x,int y){//求x,y最小公共祖先
	    if(d[x]<d[y])swap(x,y);//保证x的深度不小于y
		int k=d[x]-d[y];
		for(int i=0;i<M;i++)
			if((1<<i)&k)
				x=f[x][i];
	if(x==y)return x;//x==y时为最小公共祖先
		for(int i=M-1;i>=0;i--)
			if(f[x][i]!=f[y][i]){
				x=f[x][i];y=f[y][i];
			}
	return f[x][0];
}
int main(){
	int T,n,i,x,y;
	scanf("%d",&T);
	while(T--){
		scanf("%d",&n);
		memset(d,0,sizeof(d));
		memset(f,0,sizeof(f));
		memset(ch,0,sizeof(ch));
		for(i=1;i<n;i++){
			scanf("%d%d",&x,&y);
			ch[x].push_back(y);
			f[y][0]=x;
		}
		for(i=1;i<=n;i++)
			if(f[i][0]==0){//找到根遍历
				dfs(i);break;
			}
			scanf("%d%d",&x,&y);
			printf("%d\n",lca(x,y));
	}
return 0;
}


 

 

 

### POJ 1330 题解 POJ 1330 是一道经典的最近公共祖先 (Least Common Ancestor, LCA) 问题。该题的核心在于如何高效地求解两节点之间的最近公共祖先。 #### 倍增算法简介 倍增方法是一种高效的在线求解 LCA 的方式,其时间复杂度为 \(O((n+q)\log n)\),其中 \(n\) 表示树中的节点数量,\(q\) 表示查询次数。此方法通过预处理的方式记录每个节点向上跳跃若干步后的父节点位置,从而加速查询过程。 具体来说,定义数组 `fa[i][j]` 表示从节点 \(i\) 向上跳 \(2^j\) 步所到达的节点编号。为了支持这一操作,我们需要满足如下递推关系: \[ \text{fa}[i][j] = \begin{cases} \text{parent}(i), & j = 0 \\ \text{fa}[\text{fa}[i][j-1]][j-1], & j > 0 \end{cases} \] 这种预处理可以通过深度优先搜索 (DFS) 完成,在 DFS 过程中同时计算每个节点的深度以及它们的倍增父节点表。 #### 查询阶段 在实际查询过程中,假设我们要查找节点 \(a\) 和 \(b\) 的最近公共祖先,则分为以下几个部分: 1. **调整深度一致** 如果当前两个节点的深度不相同,则将较深的节点不断向上提升至两者深度相等的位置。这一步利用了倍增数组 `fa[i][j]` 来快速跳跃多个层次。 2. **同步爬升** 当两个节点处于同一深度时,让它们逐步向上移动直至相遇于某个共同祖先处。为了避免逐层遍历带来的效率低下问题,同样采用倍增策略按指数级跳跃。 最终返回的结果即为最后一次未分叉前的状态作为答案。 以下是基于以上逻辑的一个简单实现代码片段: ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = 5e4 + 5; vector<int> adj[MAXN]; int depth_[MAXN]; // 存储每个结点的深度 int fa[MAXN][20]; // 记录每个结点向上跳2^k步的父亲 void dfs(int u, int parent){ depth_[u]=depth_[parent]+1; fa[u][0]=parent; for(auto v : adj[u]){ if(v != parent){ dfs(v,u); } } } // 初始化fa[][]表格 void preprocess(int N){ memset(fa,-1,sizeof(fa)); for(int k=1;k<20;k++){ for(int i=1;i<=N;i++){ if(fa[i][k-1]!=-1){ fa[i][k]=fa[fa[i][k-1]][k-1]; } } } } int get_lca(int a,int b){ if(depth_[a]<depth_[b]) swap(a,b); // 将a提到和b相同的高度 for(int k=19;k>=0;k--){ if(fa[a][k]!=-1 && depth_[fa[a][k]] >= depth_[b]){ a=fa[a][k]; } } if(a==b)return a; // 同步爬升 for(int k=19;k>=0;k--){ if(fa[a][k]!=-1 && fa[b][k]!=-1 && fa[a][k]!=fa[b][k]){ a=fa[a][k]; b=fa[b][k]; } } return fa[a][0]; } ``` 上述程序实现了完整的倍增法用于解决LCA问题的功能模块化设计[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值