POJ.1330 Nearest Common Ancestors (LCA 倍增)
来源:互联网 发布:大数据交易平台 编辑:程序博客网 时间:2024/06/10 08:42
POJ.1330 Nearest Common Ancestors (LCA 倍增)
题意分析
给出一棵树,树上有n个点(n-1)条边,n-1个父子的边的关系a-b。接下来给出xy,求出xy的lca节点编号。
LCA裸题,用倍增思想。
代码总览
#include <cstdio>#include <algorithm>#include <cstring>#include <cmath>#define nmax 80520#define demen 25using namespace std;int fa[nmax][demen],head[nmax],dep[nmax];int n,m,tot = 0;struct node{ int to; int next; int w;}edge[nmax];void add(int u, int v){ edge[tot].to = v; edge[tot].next = head[u]; head[u] = tot++;}void dfs(int rt,int f){ fa[rt][0] = f; for(int i = 1;i<=20;++i){ fa[rt][i] = fa[fa[rt][i-1]][i-1]; } for(int i = head[rt];i!=-1;i = edge[i].next){ int nxt = edge[i].to; if(nxt != f){ dep[nxt] = dep[rt] + 1; dfs(nxt,rt); } }}int lca(int x, int y){ int X = x,Y=y; if(dep[x] < dep[y]) swap(x,y); int dis = dep[x] - dep[y]; for(int i = 20;i>=0;--i){ if((1<<i) & dis) x = fa[x][i]; } if(x == y) return(x); for(int i = 20;i>=0;--i){ if(fa[x][i] != fa[y][i]){ x = fa[x][i],y = fa[y][i]; } } return(fa[x][0]);}void init(){ memset(fa,0,sizeof fa); memset(head,-1,sizeof head); memset(dep,0,sizeof dep); tot = 0;}int main(){ int t; scanf("%d",&t); while(t--){ init(); int n,u,v; scanf("%d",&n); int root = 0; for(int i = 0;i<n-1;++i){ scanf("%d %d",&u,&v); if(root == 0) root = u; add(u,v); add(v,u); } dep[root] = 1; dfs(root,0); scanf("%d %d",&u,&v); printf("%d\n",lca(u,v)); } return 0;}
阅读全文
0 0
- Poj-1330-Nearest Common Ancestors-倍增LCA
- POJ.1330 Nearest Common Ancestors (LCA 倍增)
- 【POJ】1330 Nearest Common Ancestors 在线LCA,倍增思想
- POJ 1330 Nearest Common Ancestors(在线倍增LCA)
- POJ 1330 Nearest Common Ancestors 倍增算法的LCA
- POJ 1330 Nearest Common Ancestors 倍增法求LCA
- poj 1330 Nearest Common Ancestors(倍增法)
- POJ-1330 Nearest Common Ancestors【LCA】
- POJ 1330 Nearest Common Ancestors [LCA+RMQ]
- POJ 1330Nearest Common Ancestors LCA模板
- poj 1330 Nearest Common Ancestors(LCA)
- POJ 1330 Nearest Common Ancestors (LCA)
- poj 1330 Nearest Common Ancestors (LCA)
- poj 1330 Nearest Common Ancestors(LCA模板)
- POJ 1330 Nearest Common Ancestors LCA
- POJ 1330 Nearest Common Ancestors LCA
- poj 1330 Nearest Common Ancestors LCA targin
- POJ 1330 Nearest Common Ancestors LCA题解
- Ubuntu 17.04编译串口发送16进制数据包报了个神奇的错误
- XListview上拉刷新,下拉加载
- POJ2528 线段树 区间更新 离散化
- 华容道
- 思考接入sdk接口的提取
- POJ.1330 Nearest Common Ancestors (LCA 倍增)
- Windows服务器启动Tomcat时,设置编码和将控制台输出到log文件
- (Visual Studio)VS2015括号颜色更改
- QAQ & ORZ 的签到题
- 多校联萌(三)小ho的01串
- RandomAccessFile的使用
- arguments
- QAQ & 君临天下 || 天行九歌
- ACM集训日记-8月11日