POJ 1330Nearest Common Ancestors LCA
来源:互联网 发布:暗影格斗2mac 编辑:程序博客网 时间:2024/06/05 22:46
POJ 1330
可以说是经典的LCA求最近公共祖先的模板题,先入门感受下LCA,还有poj运行STL会WA,所以建议使用静态连接的邻接表做,还有codeforces的#include<bits/stdc++.h>头文件也不支持。
代码如下:
#include<cstdio>#include<vector>#include<algorithm>#include<cstring>using namespace std;typedef long long LL;#define INF 0x3f3f3f3fconst int MAXN=10005;int q1,q2,father[MAXN],res,indeg[MAXN];struct Edge{ int to; Edge *next;}e[MAXN*2],*cur,*adj[MAXN];void addEdge(Edge *head[],int u,int v){ cur->to=v; cur->next=head[u]; head[u]=cur++;}int findset(int u){ if(father[u]==u) return u; return father[u]=findset(father[u]);}void Tarjan(int u){ father[u]=u; for(Edge *it=adj[u];it;it=it->next) { int to=it->to; Tarjan(to); father[to]=u; } if(u==q1||u==q2) { if(u!=q1) swap(q1,q2); if(father[q2]) res=findset(father[q2]); }}void init(int n){ for(int i=0;i<=n;i++) { adj[i]=NULL; indeg[i]=0;father[i]=0; } cur=e;}int main(){ int t; scanf("%d",&t); while(t--) { int n,u,v; scanf("%d",&n); init(n); for(int i=1;i<n;i++) { scanf("%d%d",&u,&v); addEdge(adj,u,v);indeg[v]++; } scanf("%d%d",&q1,&q2); for(int i=1;i<=n;i++) { if(indeg[i]==0) { Tarjan(i);break; } } printf("%d\n",res); }}
0 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之旅(四)--ViewPage(1)
- KMP算法的经典例题(poj 3461、poj 2752、poj 2406、poj1961)
- ubuntu中root和普通用户切换
- Spring MVC 传递参数二
- solr 5.0.0 + tomcat7 安装 + IKAnalyzer中文分词
- POJ 1330Nearest Common Ancestors LCA
- Java虚拟机--编译期优化
- 安装Ubuntu后的系统设置
- Extjs:解决<iframe>中src被加载两次第二次加载时无法获取参数值的一种方法
- 欢迎使用CSDN-markdown编辑器
- 【学习交流】工作之余看点书,实现仿酷欧天气,欢迎交流~
- 统计字符串中字符个数
- CSS学习笔记--Div+Css布局实战(入门)
- Linux 关闭防火墙