A. Nearest Common Ancestors

Time Limit: 1000ms
Case Time Limit: 1000ms
Memory Limit: 10000KB
 
64-bit integer IO format: %lld      Java class name: Main
 
 
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 解题:本来打算用dfs+RMQ写的,结果写得一塌糊涂,完全不对。后来发现只有一个询问,即为了这一次询问可以破坏原有结构。直接暴力好了。
 #include <iostream>
#include <cstdio>
using namespace std;
bool vis[];
int uf[];
int main() {
int ks,n,i,x,y;
scanf("%d",&ks);
while(ks--) {
scanf("%d",&n);
for(i = ; i <= n; i++) {
vis[i] = false;
uf[i] = i;
}
for(i = ; i < n; i++) {
scanf("%d %d",&x,&y);
uf[y] = x;
}
scanf("%d %d",&x,&y);
vis[x] = true;
x = uf[x];
while(x != uf[x]) {
vis[x] = true;
x = uf[x];
}
while(y != uf[y]) {
if(vis[y]) break;
y = uf[y];
}
printf("%d\n",y);
}
return ;
}

倍增法求LCA

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <cstdlib>
#include <string>
#include <set>
#include <stack>
#define LL long long
#define pii pair<int,int>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = ;
int n,deep[maxn],fa[maxn][];
vector<int>g[maxn];
void dfs(int u,int f){
for(int i = ; i < g[u].size(); i++){
if(g[u][i] == f) continue;
deep[g[u][i]] = deep[u]+;
dfs(g[u][i],u);
}
}
void init(){
for(int j = ; j < ; j++){
for(int i = ; i <= n; i++)
fa[i][j] = fa[fa[i][j-]][j-];
}
}
int LCA(int u,int v){
if(deep[u] < deep[v]) swap(u,v);
int i,d = deep[u]-deep[v];
for(i = ; i < ; i++) if((<<i)&d) u = fa[u][i];
if(u == v) return u;
for(i = ; i >= ; i--){
if(fa[u][i] != fa[v][i]){
u = fa[u][i];
v = fa[v][i];
}
}
return fa[u][];
}
int main() {
int t,i,u,v,root;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(i = ; i <= n; i++){
g[i].clear();
deep[i] = ;
}
memset(fa,,sizeof(fa));
for(i = ; i < n; i++){
scanf("%d %d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
fa[v][] = u;
if(!fa[u][]) root = u;
}
deep[root] = ;
dfs(root,-);
init();
scanf("%d %d",&u,&v);
printf("%d\n",LCA(u,v));
}
return ;
}

tarjan求LCA

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <cstdlib>
#include <string>
#include <set>
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = ;
vector<int>g[maxn];
int n,x,y,uf[maxn],ans;
bool vis[maxn];
int Find(int rt) {
if(rt != uf[rt])
uf[rt] = Find(uf[rt]);
return uf[rt];
}
bool dfs(int u) {
uf[u] = u;
for(int i = ; i < g[u].size(); i++) {
if(!vis[g[u][i]]) {
if(dfs(g[u][i])) return true;
uf[g[u][i]] = u;
}
}
if(u == x && vis[y]) {
ans = Find(y);
return true;
} else if(u == y && vis[x]) {
ans = Find(x);
return true;
}
vis[u] = true;
return false;
}
int main() {
int t,i,u,v,root;
scanf("%d",&t);
while(t--) {
scanf("%d",&n);
for(i = ; i <= n; i++) {
g[i].clear();
vis[i] = false;
}
for(i = ; i < n; i++) {
scanf("%d %d",&u,&v);
g[u].push_back(v);
vis[v] = true;
}
for(i = ; i <= n; i++)
if(!vis[i]) {
root = i;
break;
}
scanf("%d%d",&x,&y);
memset(vis,false,sizeof(vis));
dfs(root);
cout<<ans<<endl;
}
return ;
}

A. Nearest Common Ancestors的更多相关文章

  1. POJ 1330 Nearest Common Ancestors(Targin求LCA)

    传送门 Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 26612   Ac ...

  2. [最近公共祖先] POJ 1330 Nearest Common Ancestors

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 27316   Accept ...

  3. POJ 1330 Nearest Common Ancestors

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 14698   Accept ...

  4. POJ1330 Nearest Common Ancestors

      Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 24587   Acce ...

  5. POJ 1330 Nearest Common Ancestors(Tree)

    题目:Nearest Common Ancestors 根据输入建立树,然后求2个结点的最近共同祖先. 注意几点: (1)记录每个结点的父亲,比较层级时要用: (2)记录层级: (3)记录每个结点的孩 ...

  6. 【POJ】1330 Nearest Common Ancestors ——最近公共祖先(LCA)

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 18136   Accept ...

  7. POJ 1330 Nearest Common Ancestors LCA题解

    Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 19728   Accept ...

  8. POJ - 1330 Nearest Common Ancestors(基础LCA)

    POJ - 1330 Nearest Common Ancestors Time Limit: 1000MS   Memory Limit: 10000KB   64bit IO Format: %l ...

  9. POJ 1330 Nearest Common Ancestors / UVALive 2525 Nearest Common Ancestors (最近公共祖先LCA)

    POJ 1330 Nearest Common Ancestors / UVALive 2525 Nearest Common Ancestors (最近公共祖先LCA) Description A ...

  10. pku 1330 Nearest Common Ancestors LCA离线

    pku 1330 Nearest Common Ancestors 题目链接: http://poj.org/problem?id=1330 题目大意: 给定一棵树的边关系,注意是有向边,因为这个WA ...

随机推荐

  1. 一个简易的Http请求转发器

    这两天一直再看微信开发,临时在我的电脑搭了个IIS服务器做微信开发,外网也能访问了,关键是,调试太麻烦了!! 我写完代码,要将代码发布到IIS才能接收微信消息,可是在这个过程中,我不知道微信发过来的是 ...

  2. 【持续更新】HTML5 基础知识

    文档类型声明 <!DOCTYPE html> 必不可少,位于文件第一行. 字符编码 <meta charset="UTF-8"> 语义化标记元素 heade ...

  3. this详解,对执行上下文说 Yes

    this 指向多变,很多隐蔽的 bug 都缘于它.与此同时,this 强大灵活,如果能熟练驾驭,就会写出更简洁.优雅的代码. 社区上对于 this 的讲解虽然不少,但缺乏统一梳理. this 相关知识 ...

  4. leetcode395 Longest Substring with At Least K Repeating Characters

    思路: 尺取法. 循环i:1~26,分别计算恰好包含i种字母并且每种字母出现的次数大于等于k个的最长子串长度. 没法直接使用尺取法,因为不满足区间单调性,但是使用如上的方法却是可以的,因为子串中包含的 ...

  5. jquery mobile 的手指上下滑动文章、导航栏

    导航栏的js设置 <!--导航栏的滚动 --> <script type="text/javascript"> var myScroll, pullDown ...

  6. 动画 iOS基础

    动画 iOS基础 1.     basic animation  基础动画 一个基础动画 在一个开始值和一个结束值之间运动   messageLabel.alpha=0.0; [UIView  ani ...

  7. PHP识别二维码功能,php-zbarcode 安装

    php-zbarcode是PHP识别二维码的扩展. 下面是安装方法,安装前要先安装ImageMagick.zbar. php-zbarcode 下载地址 安装ImageMagick: yum inst ...

  8. -[UPAInitViewController startAPPay] in libUPAPayPlugin.a(UPAInitViewController.o)

    问题 Undefined symbols for architecture arm64: "_PKPaymentNetworkChinaUnionPay", referenced ...

  9. 强化学习_Deep Q Learning(DQN)_代码解析

    Deep Q Learning 使用gym的CartPole作为环境,使用QDN解决离散动作空间的问题. 一.导入需要的包和定义超参数 import tensorflow as tf import n ...

  10. windows/Linux 常用命令

    windows 文件操作命令 cd 切换文件目录 dir 显示文件目录内容 md 创建文件夹 rd 删除文件夹 copy 拷贝文件 move 移动文件 del 删除文件 replace 替换文件 mk ...