poj1330 Nearest Common Ancestors
来源:互联网 发布:佳能小型打印机软件 编辑:程序博客网 时间:2024/05/08 05:12
题目链接:..G20过了再补
题目大意:求最近公共祖先...水..
题解:倍增LCA/树剖
就是练模版的题...话说看了一下,我的树剖比倍增还快了那么一丢丢..
注意:不是无根树啊233
#include<cstdio>#include<cstring>#include<iostream>#include<cstdlib>#include<iostream>#include<algorithm>using namespace std;#define maxn 20100struct node{int x,y,next;}a[maxn];int len,first[maxn];void ins(int x,int y){len++;a[len].x=x;a[len].y=y;a[len].next=first[x];first[x]=len;}int fa[maxn],son[maxn],dep[maxn];int tot[maxn],top[maxn];void dfs1(int x){son[x]=0;tot[x]=1;for (int k=first[x];k!=-1;k=a[k].next){int y=a[k].y;if (y!=fa[x]){fa[y]=x;dep[y]=dep[x]+1;dfs1(y);if (tot[son[x]]<tot[y]) son[x]=y;tot[x]+=tot[y];}}}void dfs2(int x,int tp){top[x]=tp;if (son[x]!=0) dfs2(son[x],tp);for (int k=first[x];k!=-1;k=a[k].next){int y=a[k].y;if (y!=fa[x] && y!=son[x]) dfs2(y,y);}}int lca(int x,int y){int ty=top[y],tx=top[x];while (tx!=ty){if (dep[tx]>dep[ty]){int tt=tx;tx=ty;ty=tt;tt=x;x=y;y=tt;}y=fa[ty];ty=top[y];}if (x==y) return x;else{if (dep[x]>dep[y]){int tt=x;x=y;y=tt;}return x;}}int main(){//freopen("a.in","r",stdin);//freopen("a.out","w",stdout);int T,n,x,y,i,rt;scanf("%d",&T);while (T--){len=0;memset(first,-1,sizeof(first));scanf("%d",&n);rt=(1+n)*n/2;for (i=1;i<n;i++){scanf("%d%d",&x,&y);ins(x,y);ins(y,x);rt-=y;}fa[rt]=0;dep[rt]=0;dfs1(rt);dfs2(rt,rt);scanf("%d%d",&x,&y);printf("%d\n",lca(x,y));}return 0;}
0 0
- POJ1330 Nearest Common Ancestors
- POJ1330(Nearest Common Ancestors)
- POJ1330--Nearest Common Ancestors
- poj1330 Nearest Common Ancestors
- Nearest Common Ancestors Poj1330
- POJ1330 Nearest Common Ancestors
- poj1330 Nearest Common Ancestors
- poj1330 Nearest Common Ancestors
- poj1330 Nearest Common Ancestors
- POJ1330(Nearest Common Ancestors)
- POJ1330 Nearest Common Ancestors[LCA]
- 【POJ1330】Nearest Common Ancestors(LCA)
- poj1330 Nearest Common Ancestors()
- poj1330——Nearest Common Ancestors
- [LCA模板]POJ1330 Nearest Common Ancestors
- poj1330 Nearest Common Ancestors pascal代码
- 倍增LCA poj1330 Nearest Common Ancestors
- poj1330 Nearest Common Ancestors (最近公共祖先)
- JAVA 百万级的数据并发SOCKET编程(已经通过测试)
- ExtJs教程----创建Store
- light oj1045 - Digits of Factorial (阶乘的位数,,运用对数)
- Visual Studio 2012出现“无法访问T-SQL组件和安装了不兼容伯 DacFx版本”的解决办法
- SharedPreferences数据处理简单实例
- poj1330 Nearest Common Ancestors
- SpringMVC日期类型转换问题三大处理方法归纳
- android之LayoutInflater的获取与使用
- 与信号相关的linux系统编程API
- 有关电容电磁触控算法软件工程师
- 用python初步计算整数和
- 正则表达式匹配不包含某个字符串
- JZOJ4760【雅礼联考GDOI2017模拟9.4】同桌的你 环套树拆边DP
- codeforces 709 D Recover the String (构造)