LCA
来源:互联网 发布:yyf的淘宝店叫什么 编辑:程序博客网 时间:2024/04/29 08:23
#include <cstdio>#include <algorithm>using namespace std;const int N = 100010;const int M = N + N;const int P = 16;int n, q;int head[N], dest[M], last[M], etot;int dep[N], anc[N][P+1];void adde( int u, int v ) { etot++; dest[etot] = v; last[etot] = head[u]; head[u] = etot;}void dfs( int u, int f ) { anc[u][0] = f; for( int p = 1; p <= P; p++ ) anc[u][p] = anc[anc[u][p-1]][p-1]; for( int t = head[u]; t; t = last[t] ) { int v = dest[t]; if( v == f ) continue; dep[v] = dep[u] + 1; dfs( v, u ); }}int lca( int u, int v ) { if( dep[u] < dep[v] ) swap(u,v); int t = dep[u] - dep[v]; /* for( int p = 0; p <= P; p++ ) if( t & (1<<p) ) u = anc[u][p]; */ for( int p = 0; p <= P; p++ ) if( t & (1<<p) ) u = anc[u][p]; for( int p = 0; t; t >>= 1, p++ ) if( t & 1 ) u = anc[u][p]; if( u == v ) return u; for( int p = P; p >= 0 /*anc[u][0] != anc[v][0]*/; p-- ) if( anc[u][p] != anc[v][p] ) u = anc[u][p], v = anc[v][p]; return anc[u][0];}int main() { scanf( "%d", &n ); for( int i = 1; i < n; i++ ) { int u, v; scanf( "%d%d", &u, &v ); adde( u, v ); adde( v, u ); } dep[1] = 1; dfs( 1, 1 ); scanf( "%d", &q ); while( q-- ) { int u, v; scanf( "%d%d", &u, &v ); printf( "%d\n", lca(u,v) ); }}
0 0
- LCA
- LCA
- lca
- LCA
- LCA
- lca
- LCA
- LCA
- LCA
- LCA
- LCA
- lca
- lca
- LCA
- lca
- LCA
- LCA
- LCA
- 准备工作!!! canvas游戏开发!!!
- Superset离线安装
- CI Weekly #12 - 微信小程序的自动化测试进阶
- echo和echo -n浪费一下午时间
- 值域线段树
- LCA
- DNS Rebinding技术绕过SSRF/代理IP限制
- 读《黑客与画家》感想(3)
- iOS block中使用self的那么事
- 尔雅慕课超星中职生安全教育(v1)答案【测试和考试】
- H5---喷泉
- 关于ELF文件的段表
- css3模拟jq点击事件
- 计算历史区间的收益率,用前复权还是后复权?