poj 1330
来源:互联网 发布:自学凸优化 编辑:程序博客网 时间:2024/06/05 12:01
LCA倍增,以前写过离线Tarjan,不多说
#include<map>#include<string>#include<cstdio>#include<cstdlib>#include<cstring>#include<ctime>#include<cmath>#include<iostream>#include<algorithm>const int MAXN = 10005 , logN = 15;int n;struct Edge{int v,next;}edge[MAXN<<1] = {0};int el = 0;int head[MAXN] = {0}, fa[MAXN][logN] = {0} , dep[MAXN] = {0};bool hash[MAXN] = {0};void newedge(int u,int v){ ++el; edge[el].v = v; edge[el].next = head[u],head[u] = el;}void build(int a){ dep[a] = dep[fa[a][0]] + 1; for(int i = head[a]; i; i = edge[i].next) { int p = edge[i].v; if(p == fa[a][0])continue; fa[p][0] = a; build(p); }}void prelca(){ for(int j = 1 ; j < logN; j++) for(int i = 1; i <= n ; i++) fa[i][j] = fa[fa[i][j-1]][j-1];}int getLCA(int u,int v){ if(dep[u] > dep[v])std::swap(u,v); for(int i = logN - 1; i >= 0 ; i--) if(dep[fa[v][i]] >= dep[u]) v = fa[v][i]; if(u == v) return u; for(int i = logN - 1; i >= 0 ; i--) if(fa[u][i] != fa[v][i])u = fa[u][i],v = fa[v][i]; return fa[v][0]; }int main(){ int T;#ifndef ONLINE_JUDGE freopen("poj1330.in","r",stdin); freopen("poj1330.out","w",stdout);#endif scanf("%d",&T); while(T--) { el = 0; memset(head,0,sizeof(head)); memset(hash,false,sizeof(hash)); int a ,b , root; scanf("%d",&n); for(int i = 1 ; i < n; i++) { scanf("%d%d",&a,&b); newedge(a,b); hash[b] = true; } for(int i = 1; i <= n; i++) if(hash[i] == false){root = i;break;} fa[root][0] = 0; build(root); prelca(); scanf("%d%d",&a,&b); printf("%d\n",getLCA(a,b)); }#ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout);#endif return 0;}
0 0
- poj 1330
- poj 1330
- poj-1330
- poj 1330
- poj 1330
- poj 1330
- POJ 1330
- POJ 1330 LCA问题
- POJ 水题 1330 LCA
- poj 1330 LCA
- poj 1330(LCA)
- Poj 1330 LCA
- poj 1330 LCA
- POJ 1330 解题报告
- (LCA倍增) poj 1330
- poj 1330 dfs树
- [LCA] POJ 1330
- POJ
- C标准库:IO错误处理
- startActivityForResult用法详解
- #笔记#圣思园 JavaSE 第4讲——运算符
- Android UI-实现底部切换标签(fragment)
- 设计模式导学目录(完整版)
- poj 1330
- CodeForces 7C Line (扩展欧几里得)
- Learn Python The Hard Way学习(16) - 读写文件
- js模拟多线程
- Zend Framework1-Zend_Db_Adapter
- CodeForces 7A Kalevitch and Chess
- Windows下字符编码转换(ANSI <--> Unicode <--> UTF-8)
- UITextView 或 继承自UIScrollView的控件在UINavigationController的根控制下的奇怪现象
- [数学模型]整数规划(一)