Poj-1330-Nearest Common Ancestors-倍增LCA
来源:互联网 发布:excel办公软件 编辑:程序博客网 时间:2024/05/29 11:04
代码很好理解(我觉得是)好吧,这么渣的代码根本就是我自己写的(ノ=Д=)ノ┻━┻
LCA倍增代码
#include <cstdio>#include <cstring>#include <cstdlib>#include <iostream>#include <vector>#include <queue>#include <algorithm> #define maxn 10010#define lg 20#define inf 0xefffffff using namespace std; vector<int> g[maxn];int f[maxn][lg + 5], d[maxn], n; void dfs(int x){ d[x] = d[f[x][0]] + 1; for (int i = 1; i <= lg; i++) f[x][i] = f[f[x][i - 1]][i - 1]; for (int i = 0; i < g[x].size(); i++) dfs(g[x][i]); return ;} inline void init(){ scanf("%d", &n); for (int i = 0; i < maxn; i++) g[i].clear(); memset(f,0,sizeof(f)); memset(d,0,sizeof(d)); int fr, to; for (int i = 1; i < n; i++) { scanf("%d %d", &fr, &to); g[fr].push_back(to); f[to][0] = fr; } for (int i = 1; i <= n; i++) if (!f[i][0]) { dfs(i); break; } return ;} inline int lca(int x, int y){ if (d[x] < d[y]) swap(x, y); int dt = d[x] - d[y]; for (int i = lg; i >= 0; i--) if ((1 << i) & dt) x = f[x][i]; if (x == y) return x; for (int i = lg; i >= 0; i--) if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i]; return f[x][0];} int main(){ int T; scanf("%d", &T); int fr, to; while (T--) { init(); scanf("%d %d", &fr, &to); printf("%d\n", lca(fr, to)); } return 0;}
0 0
- 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(倍增法)
- 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题解
- [SPOJ]-1481-寻找素数项-miller rabin
- [USACO]-4.2-完美的牛栏-二分图匹配
- iOS XMPP Framework 07 - 收发消息 上
- 关于FMDB 数据库自己看着学的,希望可以互相学习
- [搬运]关于扩展欧几里得与同余方程
- Poj-1330-Nearest Common Ancestors-倍增LCA
- lazarus(ct版)自带的一个超级酷的三维动画例子截图
- vijos 1034 家族
- TENSE(时态)
- NYOJ-214(动态规划)-题目----------------------------- 单调递增子序列(二)
- poj3368
- [Poj]-1679-The Unique MST-N久没写代码的后果╮( ̄▽ ̄)╭
- UIKit基础:10.纯代码的实现Transform和平移VIew的功能
- 本地Service的onBind方法使用