POJ-1470-Closest Common Ancestors 解题报告
来源:互联网 发布:linux vps 教程 编辑:程序博客网 时间:2024/05/16 01:13
LCA简单基础入门题。赤裸裸的求LCA的题,不过输入比较麻烦。题意:其实看图加样例就能懂了,不多说了,最后输出每个节点成为括号内节点LCA的节点id和次数,次数为0就不输出了。
我的解题思路:用Tarjan的离线算法最后把答案哈希输出就ok了,关于此算法的原理等见请看上一个解题报告。
我的解题代码:离线求LCA算法
#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>#include <vector>using namespace std;#define N 1000bool root[N]; //判断是否根节点bool vis[N];int father[N]; //幷查集使用int lca[N]; //LCAint ans[N];vector <int> e[N]; //存储子节点vector <int> q[N]; //存储询问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;}
0 0
- POJ-1470-Closest Common Ancestors 解题报告
- POJ 1470 Closest Common Ancestors
- poj 1470 Closest Common Ancestors
- POJ 1470 Closest Common Ancestors
- poj 1470 Closest Common Ancestors
- poj 1470 Closest Common Ancestors
- POJ 1470 Closest Common Ancestors
- poj - 1470 - Closest Common Ancestors
- POJ 1470 Closest Common Ancestors
- poj 1470 Closest Common Ancestors
- poj 1470 Closest Common Ancestors
- POJ 1470 Closest Common Ancestors
- POJ---1470- Closest Common Ancestors
- POJ 1470Closest Common Ancestors
- POJ 1470 Closest Common Ancestors
- POJ 1470 Closest Common Ancestors
- POJ 1470Closest Common Ancestors
- POJ-1330-Nearest Common Ancestors 解题报告
- 王飓:SDN控制器集中群中的分布式技术实践
- Ubuntu 14.04 (32位)上搭建Hadoop 2.5.1单机和伪分布式环境
- 数据块dump详解及大小表扫描过程
- 理解Quartz触发器
- Build Cookbook
- POJ-1470-Closest Common Ancestors 解题报告
- HIVE的一些常用命令和语法
- asp.net mvc+esayui解决Date类型传值
- 史上最详细的CocoaPods安装教程
- Android中AsyncTask的函数调用顺序
- DBCP、C3P0、Proxool 、 BoneCP开源连接池的比较
- android-async-http我的使用
- C# 经典排序算法大全
- 【软考】前缀、中缀、后缀表达式