poj 1330 Nearest Common Ancestors
来源:互联网 发布:未来大数据对中国影响 编辑:程序博客网 时间:2024/06/15 19:30
一道典型的lca问题,这一道用tarjan算法即可解决。
详情参照了这篇博客:
LCA问题的Tarjan算法 » NoAlGo博客 http://noalgo.info/476.html
#include <iostream>#include <vector>#include <algorithm>#include <cstdio>using namespace std;#define max_n 10007vector<int> tree[max_n];//构建树 int qa,qb;//查询 int ancestor[max_n];//暂存最近的祖先 int indeg[max_n];//入度,判断根节点int father[max_n];//并查集 bool book[max_n];//访问标志 int n;//顶点个数int root;//根void input(){int i;int a,b;scanf("%d",&n);for(i=1;i<=n;i++){tree[i].clear();indeg[i] = 0;father[i] = i;book[i] = 0;}for(i=1;i<n;i++){scanf("%d%d",&a,&b);tree[a].push_back(b);indeg[b]++;}for(i=1;i<=n;i++){if(indeg[i]==0){root = i;break;}}scanf("%d%d",&qa,&qb); } int find(int x){if(x!=father[x])father[x] = find(father[x]);return father[x];}void get_in(int a,int b){int x = find(a);int y = find(b);if(x!=y)father[y] = x;}void tarjan(int nroot) {int i;for(i=0;i<tree[nroot].size();i++){tarjan(tree[nroot][i]);get_in(nroot,tree[nroot][i]);ancestor[find(nroot)] = nroot; }book[nroot] = true;if(nroot==qa){if(book[qb]){printf("%d\n",ancestor[find(qb)]);}} if(nroot==qb){if(book[qa]){printf("%d\n",ancestor[find(qa)]);}}}int main(){int i;scanf("%d",&i);while(i--){input();tarjan(root);}}
0 0
- POJ 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors
- poj - 1330 - Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- POJ 1330:Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors
- POJ---1330-Nearest Common Ancestors
- POJ 1330 Nearest Common Ancestors
- poj 1330 Nearest Common Ancestors
- 快速排序
- TabHosts导航按钮实现自定义图片和文字
- 【New AKOJ】1192: 最长平台
- 【NYOJ】[23]取石子(一)
- poj 2431 Expedition
- poj 1330 Nearest Common Ancestors
- 崔希凡javaWeb笔记day01~day03(2016年5月20日20:39:04)
- hdoj-5680-zxa and set
- JDBC中的setFetchSize()
- 内部类、异常知识点总结
- 设计模式 - Adapter模式
- nyoj 163 Phone List && poj 3630 Phone List <字典树 动态建树&&静态建树>
- 认真学spring官网,很容易找到spring4的jar包下载位置
- Java 设计模式 -- 职责链模式