POJ-1470-Closest Common Ancestors 解题报告
2014-10-22 16:18
399 查看
LCA简单基础入门题。赤裸裸的求LCA的题,不过输入比较麻烦。题意:其实看图加样例就能懂了,不多说了,最后输出每个节点成为括号内节点LCA的节点id和次数,次数为0就不输出了。
我的解题思路:用Tarjan的离线算法最后把答案哈希输出就ok了,关于此算法的原理等见请看上一个解题报告。
我的解题代码:离线求LCA算法
我的解题思路:用Tarjan的离线算法最后把答案哈希输出就ok了,关于此算法的原理等见请看上一个解题报告。
我的解题代码:离线求LCA算法
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm> #include <vector> using namespace std; #define N 1000 bool root ; //判断是否根节点 bool vis ; int father ; //幷查集使用 int lca ; //LCA int ans ; vector <int> e ; //存储子节点 vector <int> q ; //存储询问 int n, qn; void InitRead(); int Find(int x); void DataProcess(int x); int main() { while (~scanf("%d", &n)) { InitRead(); for (int i=1; i<=n; ++i) { if (root[i]) { DataProcess(i); break; } } for (int i=1; i<=n; ++i) { if (ans[i] != 0) { printf("%d:%d\n", i, ans[i]); } } } return 0; } void InitRead() { for (int i=0; i<=n; ++i) { root[i] = true; vis[i] = false; father[i] = i; ans[i] = lca[i] = 0; e[i].clear(); q[i].clear(); } int a, b, c; for (int i=0; i<n; ++i) { scanf("%d:(%d)", &a, &b); while (b--) { scanf("%d", &c); e[a].push_back(c); root[c] = false; } } scanf("%d", &qn); while (qn--) { scanf(" (%d %d)", &a, &b); q[a].push_back(b); q[b].push_back(a); } return; } int Find(int x) { int z, y = x; while (y != father[y]) y = father[y]; while (x != father[x]) { z = father[x]; father[x] = y; x = z; } return y; } void DataProcess(int x) { lca[x] = x; int size = e[x].size(); for (int i=0; i<size; ++i) { DataProcess(e[x][i]); father[e[x][i]] = x; } vis[x] = true; size = q[x].size(); for (int i=0; i<size; ++i) { if (vis[q[x][i]]) ans[lca[Find(q[x][i])]]++; //把答案哈希 } return; }
相关文章推荐
- Poj1470 Closest Common Ancestors LCA
- Closest Common Ancestors---poj1470(LCA+离线算法)
- poj 1470 || zoj 1141 Closest Common Ancestors (LCA)
- POJ-1470 Closest Common Ancestors【LCA】
- poj1470 Closest Common Ancestors
- poj----(1470)Closest Common Ancestors(LCA)
- poj 1470 Closest Common Ancestors(tarjan离线求lca)
- 【LCA基础】poj 1470 Closest Common Ancestors
- POJ 1470 Closest Common Ancestors 采用树结构的非线性表编程
- poj 1470:Closest Common Ancestors(最近公共祖先,Tarjan模版)
- POJ 1470 Closest Common Ancestors(LCA)
- poj1470——Closest Common Ancestors//LCA
- [POJ 1470]Closest Common Ancestors[离线LCA]
- poj1470-Closest Common Ancestors(LCA)
- 【LCA最近公共祖先】 poj1470 Closest Common Ancestors
- POJ - 1470 Closest Common Ancestors(LCA离线)
- POJ 1470 Closest Common Ancestors
- POJ 1470 Closest Common Ancestors LCA_Tarjan
- poj 1470 Closest Common Ancestors (LCA)
- POJ1470 Closest Common Ancestors 【Tarjan的LCA】