poj 1330 Nearest Common Ancestors(LCA)
来源:互联网 发布:hive查询避免数据倾斜 编辑:程序博客网 时间:2024/04/29 18:24
题目链接:http://poj.org/problem?id=1330
题意:给出一颗树,最后寻问两个点的最近公共祖先。
可以用LCA来解决,没什么问题。
#include<iostream>#include<cstdio>#include<cstring>#include<vector>using namespace std;#define clr(a,b) memset(a,b,sizeof(a))const int M = 10005;int h[M],num[M],nex[M],pos;int father[M],ancestor[M],degree[M];bool flag[M];int s,t;void init(){ clr(degree,0); clr(flag,false); clr(h,-1); pos = 0; clr(father,-1);}void add(int u,int v){ num[pos] = v; nex[pos] = h[u]; h[u] = pos++;}void make_set(int x){ father[x] = x;}int find(int x){ if(father[x] == x) return x; return father[x] = find(father[x]);}void Union(int a,int b){ father[find(b)] = find(a);}void LCA(int u){ ancestor[u] = u; make_set(u); for(int i = h[u];i != -1;i = nex[i]) { LCA(num[i]); Union(num[i],u); ancestor[ find(u) ] = u; } flag[u] = true; if(s == u && flag[t]) { cout<<ancestor[ find(t) ]<<endl; } if(t == u && flag[s]) { cout<<ancestor[ find(s) ]<<endl; }}int main(){ int n,T; cin>>T; while(T--) { cin>>n; init(); int u,v; for(int i = 0;i < n-1;++i) { cin>>u>>v; add(u,v); degree[v]++; } cin>>s>>t; for(int i = 1;i <= n;++i) { if(!degree[i]) LCA(i); } } return 0;}
参考代码:
- 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题解
- poj 1330 Nearest Common Ancestors (LCA)
- Nearest Common Ancestors - POJ 1330 LCA
- 【LCA】 POJ 1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors LCA
- POJ 1330 Nearest Common Ancestors (LCA)
- POJ 1330 Nearest Common Ancestors (LCA)
- Poj-1330-Nearest Common Ancestors-倍增LCA
- 让Android的WebView支持WebSocket
- IncludeMultipleStrutsConfigurationFiles
- IOS-常用正则表达式
- HTTP 错误 500.21 - Internal Server Error PageHandlerFactory-Integrated
- 软驱导致 windows 7 安装过程变慢
- poj 1330 Nearest Common Ancestors(LCA)
- Xen Event Channel
- 伤感日志:但我的结局是不幸福的
- centos 开启 关闭 ping(icmp) 响应
- vim 光标移动命令
- mysql 用户授权
- 值得收藏的计算机网站 【一直更新】
- linux内核空间 打开、读、写等文件操作实现
- 关于c++中虚函数和接口的关系区分(简单)