POJ 1470 Closest Common Ancestors(最近公共祖先)
来源:互联网 发布:钱龙分析软件 编辑:程序博客网 时间:2024/05/18 03:21
m次查询,每对括号里面的数都有一个最近公共祖先,最后输出各个最近祖先出现次数。
题目链接:http://poj.org/problem?id=1470
#include <iostream>#include <string.h>#include <stdio.h>#include <vector>using namespace std;const int N = 10005;int n;vector<int> vec[N];int pre[N];bool vis[N];bool root[N];int u,v;int Find(int x){ if(pre[x] != x) pre[x] = Find(pre[x]); return pre[x];}void Union(int x,int y){ x = Find(x); y = Find(y); if(x == y) return; pre[y] = x;}void LCA(int par){ for(int i=0; i<vec[par].size(); i++) { LCA(vec[par][i]); Union(par,vec[par][i]); } vis[par] = true; if(par == u && vis[v] == true) { printf("%d\n",Find(v)); return; } if(par == v && vis[u] == true) { printf("%d\n",Find(u)); return; }}int main(){ int T; scanf("%d",&T); while(T--) { scanf("%d",&n); for(int i=0; i<N; i++) { vec[i].clear(); pre[i] = i; root[i] = true; vis[i] = false; } for(int i=1; i<n; i++) { int a,b; scanf("%d%d",&a,&b); vec[a].push_back(b); root[b] = false; } scanf("%d%d",&u,&v); for(int i=1; i<=n; i++) { if(root[i] == true) { LCA(i); break; } } } return 0;}
0 0
- Closest Common Ancestors+poj+最近公共祖先
- POJ 1470 Closest Common Ancestors 最近公共祖先
- POJ 1470 Closest Common Ancestors【最近公共祖先LCA】
- POJ 1470 Closest Common Ancestors(最近公共祖先)
- poj 1470:Closest Common Ancestors(最近公共祖先,Tarjan模版)
- POJ 1470 Closest Common Ancestors B 求最近公共祖先个数
- TOJ 3033 ZOJ 1141 POJ 1470 Closest Common Ancestors / 最近公共祖先
- poj1470 Closest Common Ancestors LCA(最近公共祖先)
- 【LCA最近公共祖先】 poj1470 Closest Common Ancestors
- [POJ 1330]Nearest Common Ancestors(LCA最近公共祖先)
- POJ 1330 Nearest Common Ancestors(最近公共祖先)
- POJ 1330 Nearest Common Ancestors 【最近公共祖先】
- 最近公共祖先(least common ancestors algorithm)
- Nearest Common Ancestors(最近公共祖先)
- LCA(least common ancestors)最近公共祖先
- 最近公共祖先(Least Common Ancestors)
- poj1330 Nearest Common Ancestors (最近公共祖先)
- POJ 1470 Closest Common Ancestors
- 浙大PTA 4-4
- Day27:Three People getting cards
- Effective Java 2.0_Item 2_中文版
- 2016*国庆
- 网络设备NAPI能力
- POJ 1470 Closest Common Ancestors(最近公共祖先)
- LightOJ1197【数学】
- 程序界面的编写--使用Xml文件进行界面的编写
- RecylerView的用法解析
- Codeforces Round #375 (Div. 2) -- E. One-Way Reform(dfs求欧拉回路)
- asa hacker
- 算法设计 -- 递归
- 浙大PTA 4-3
- Java接口中的成员变量为什么必须是public static final?