POJ 1330 Nearest Common Ancestors LCA题解
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 19728 | Accepted: 10460 |
Description
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
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
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
本题是一个多叉树,然后求两点的近期公共单亲节点。
就是典型的LCA问题。这是一个非常多解法的,并且被研究的非常透彻的问题。
原始的解法:从根节点往下搜索,若果搜索到两个节点分别在一个节点的两边。那么这个点就是近期公共单亲节点了。
Trajan离线算法:首次找到两个节点的时候,假设记录了他们的最低单亲节点,那么答案就是这个最低的单亲节点了。
问题是怎样有效记录这个最低单亲节点,并有效依据遍历的情况更新,这就是利用Union Find(并查集)记录已经找到的节点,并及时更新最新訪问的节点的当前最低单亲节点。
就是并查集的灵活运用啦,假设学会了并查集那么学这个算法是不难的了。
2015-1-24 update:
以下括号的分析好像有点问题:
(以下是简单思路差点儿相同是暴力法的解法,只是事实上相对本题来说就是一次查询,故此这个也是不错的方法,并且平均时间效率只是O(lgn),应该是非常快的了。
只是有思想和这个差点儿相同的。可是更加省内存的方法,就是从须要查找的节点往单亲节点查找,那么速度是一样的,只是省内存,由于仅仅须要记录一个父母节点就能够了。并且程序会简洁点。)
这种方法的基本思想是:
如果要查找u,v的LCA,
递归深度遍历整棵树,这个时候有三种情况:
1. 假设没哟找到u或者v当中一个节点。那么就返回0;
2 假设找到了u或v的当中一个节点。那么就返回找到的节点
3 假设找到u且找到v两个节点。那么就返回其父母节点。而这个父母节点正好是LCA,为什么呢?由于这个是逐层递归上去的算法,仅仅有在u和v的分叉节点能找到两个非零返回值,其它情况都仅仅能找到一个或者0个非零返回值。巧妙地利用了递归的特点。把LCA作为了终于的返回值。
由于最坏情况须要递归整棵树。故此这个算法的时间效率事实上是O(n),n为整棵树的节点数。
故此本算法尽管AC了,可是事实上时间效率还是蛮低的。
之前分析说是O(lgn)是不正确的。不好意思。假设误导了某些读者,那么表示抱歉。
还好以下算法是没错的。
本算法对递归的理解还是要求挺高的,对于刚開始学习的人还是有点难度。
int const MAX_N = 10001; struct Node
{
bool notRoot;
vector<int> children;
}; Node Tree[MAX_N];
int N; int find(int r, int lNode, int rNode)
{
if (!r) return 0;
if (r == lNode) return r;
if (r == rNode) return r; vector<int> found;
for (int i = 0; i < (int)Tree[r].children.size(); i++)
{
found.push_back(find(Tree[r].children[i], lNode, rNode));
}
int u = 0, v = 0;
for (int i = 0; i < (int)found.size(); i++)
{
if (found[i] != 0)
{
if (u) v = found[i];
else u = found[i];
}
}
if (v) return r;
return u;
} void solve()
{
scanf("%d", &N);
memset(Tree, 0, sizeof(Tree)); int u, v;
for (int i = 1; i < N; i++)
{
scanf("%d %d", &u, &v);
Tree[u].children.push_back(v);
Tree[v].notRoot = 1;
}
int root = 0;
for (int i = 1; i <= N; i++)
{
if (!Tree[i].notRoot)
{
root = i;
break;
}
} scanf("%d %d", &u, &v);
int r = find(root, u, v);
printf("%d\n", r);//if (lin && rin) 必定是存在点。故此无需推断
} int main()
{
int T;
scanf("%d", &T);
while (T--)
{
solve();
}
return 0;
}
以下是Tarjan离线算法,效率应该和上面是一样的。多次查询的时候就能提高效率。只是实际执行比上面快。
#include <stdio.h>
#include <string.h>
#include <vector>
using std::vector;
int const MAX_N = 10001; struct Node
{
bool notRoot;
bool vis;
vector<int> children;
}; Node Tree[MAX_N];
int N;
int u, v;
int parent[MAX_N]; inline int find(int x)
{
if (!parent[x]) return x;
return parent[x] = find(parent[x]);
} inline void unionTwo(int p, int x)
{
p = find(p);
x = find(x);
if (p == x) return ;
parent[x] = p;
} bool LCATarjan(int root)
{
Tree[root].vis = true;
if (root == u && Tree[v].vis == true)
{
printf("%d\n", find(v));
return true;
}
if (root == v && Tree[u].vis == true)
{
printf("%d\n", find(u));
return true;
}
for (int i = 0; i < (int)Tree[root].children.size(); i++)
{
if (LCATarjan(Tree[root].children[i])) return true;
unionTwo(root, Tree[root].children[i]);
}
return false;
} void solve()
{
scanf("%d", &N);
memset(Tree, 0, sizeof(Tree));
memset(parent, 0, sizeof(parent)); for (int i = 1; i < N; i++)
{
scanf("%d %d", &u, &v);
Tree[u].children.push_back(v);
Tree[v].notRoot = 1;
}
int root = 0;
for (int i = 1; i <= N; i++)
{
if (!Tree[i].notRoot)
{
root = i;
break;
}
}
scanf("%d %d", &u, &v);
LCATarjan(root);
} int main()
{
int T;
scanf("%d", &T);
while (T--)
{
solve();
}
return 0;
}
POJ 1330 Nearest Common Ancestors LCA题解的更多相关文章
- POJ.1330 Nearest Common Ancestors (LCA 倍增)
POJ.1330 Nearest Common Ancestors (LCA 倍增) 题意分析 给出一棵树,树上有n个点(n-1)条边,n-1个父子的边的关系a-b.接下来给出xy,求出xy的lca节 ...
- poj 1330 Nearest Common Ancestors lca 在线rmq
Nearest Common Ancestors Description A rooted tree is a well-known data structure in computer scienc ...
- poj 1330 Nearest Common Ancestors LCA
题目链接:http://poj.org/problem?id=1330 A rooted tree is a well-known data structure in computer science ...
- POJ 1330 Nearest Common Ancestors (LCA,倍增算法,在线算法)
/* *********************************************** Author :kuangbin Created Time :2013-9-5 9:45:17 F ...
- POJ 1330 Nearest Common Ancestors(LCA模板)
给定一棵树求任意两个节点的公共祖先 tarjan离线求LCA思想是,先把所有的查询保存起来,然后dfs一遍树的时候在判断.如果当前节点是要求的两个节点当中的一个,那么再判断另外一个是否已经访问过,如果 ...
- POJ - 1330 Nearest Common Ancestors(基础LCA)
POJ - 1330 Nearest Common Ancestors Time Limit: 1000MS Memory Limit: 10000KB 64bit IO Format: %l ...
- POJ 1330 Nearest Common Ancestors / UVALive 2525 Nearest Common Ancestors (最近公共祖先LCA)
POJ 1330 Nearest Common Ancestors / UVALive 2525 Nearest Common Ancestors (最近公共祖先LCA) Description A ...
- POJ 1330 Nearest Common Ancestors(lca)
POJ 1330 Nearest Common Ancestors A rooted tree is a well-known data structure in computer science a ...
- POJ 1330 Nearest Common Ancestors 倍增算法的LCA
POJ 1330 Nearest Common Ancestors 题意:最近公共祖先的裸题 思路:LCA和ST我们已经很熟悉了,但是这里的f[i][j]却有相似却又不同的含义.f[i][j]表示i节 ...
随机推荐
- zoj 2110
这道题困扰我的不是算法问题.而是细节问题.不优化一直搜到底 时间是690ms左右 没有优化的dfs #include<stdio.h> #include<string.h> # ...
- JavaSE_ 多线程 总目录(23~24)
JavaSE学习总结第23天_多线程123.01 多线程程序的引入23.02 进程概述及多进程的意义23.03 线程概述及多线程的意义23.04 并行和并发的区别23.05 Java程序运行原理和JV ...
- mac上搭建svn服务器
1.terminal 执行svnadmin create 库地址/库名,生成的即为svn库根地址. 2.修改对应目录下conf/svnserve.conf文件: anon-access = read ...
- Oracle不能导入空表解决方案
C:\Users\Administrator>sqlplus / as sysdba SQL*Plus: Release 11.2.0.1.0 Production on 星期日 8月 17 1 ...
- Teclast/台电 P98HD四核测评9.7寸台电P98HD 评测体验 (转载)
自从苹果新iPad上市推出后,拥有Retina高清屏幕分辨率的平板让我们的视线一下子变得“清晰”起来,超高2048x1536分辨率也成为厂商们追捧的对象,在经历了双核时代配备高清分辨率对于硬件性能承载 ...
- QT窗口拖拽功能简单应用(处理dragEnterEvent和dropEvent事件,不同的事件有不同的信息,比如mimeData)
void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); ui->lineEdit-> ...
- Spring Cache使用详解
Spring Cache Spring Cache使用方法与Spring对事务管理的配置相似.Spring Cache的核心就是对某个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用 ...
- python开发_大小写转换,首字母大写,去除特殊字符
这篇blog主要是总结我们在平常开发过程中对字符串的一些操作: #字母大小写转换 #首字母转大写 #去除字符串中特殊字符(如:'_','.',',',';'),然后再把去除后的字符串连接起来 #去除' ...
- live555学习经验链接二
live555学习经验链接二:http://blog.csdn.net/nkmnkm/article/category/1066093/2
- Node log4js
一个完善的项目,日志是必不可少的一部分,在node开发中,调试成了让开发者头疼的部分,因此日志成为在node中帮助调试的一个重要模块. 一.Node使用Log4js 1.使用npm工具,在命令行中 执 ...