poj1330-Nearest Common Ancestors
训练暑期课面向全球招生,欲报名从速!
Language: Default Nearest Common Ancestors
Description A rooted tree is a well-known data structure in computer science and engineering. An example is shown below: In the figure, each node is labeled with an integer from {1, 2,...,16}. Node 8 is the root of the tree. Node x is an ancestor of node y if node x is in the path between the root and node y. For example, node 4 is an ancestor of node 16. Node 10 is also an ancestor For other examples, the nearest common ancestor of nodes 2 and 3 is node 10, the nearest common ancestor of nodes 6 and 13 is node 8, and the nearest common ancestor of nodes 4 and 12 is node 4. In the last example, if y is an ancestor of z, then the nearest Write a program that finds the nearest common ancestor of two distinct nodes in a tree. Input The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case starts with a line containing an integer N , the number of nodes in a tree, 2<=N<=10,000. The nodes are labeled with integers 1, 2,..., Output Print exactly one line for each test case. The line should contain the integer that is the nearest common ancestor. Sample Input 2 16 1 14 8 5 10 16 5 9 4 6 8 4 4 10 1 13 6 15 10 11 6 7 10 2 16 3 8 1 16 12 16 7 5 2 3 3 4 3 1 1 5 3 5 Sample Output 4 3 Source |
倍增
code:
<span style="font-size:18px;">#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <algorithm> using namespace std; #define rep(i, l, r) for (int i = l; i <= r; i++) #define REP(i, l, r) for (int i = l; i >= r; i--) #define M 10 #define MAXN 50010 int n, fa[MAXN][M+5], root, dep[MAXN], N, first[MAXN], next[MAXN], T_T; bool vis[MAXN]; struct tlist {int x, y;} a[MAXN];//数组模拟临接表 inline void add(int x, int y) {a[++N].x = x, a[N].y = y, next[N] = first[x], first[x] = N;} inline void swap(int &a, int &b) {int t = a; a = b; b = t;} inline void dfs(int x, int d) {//求每个节点的深度 vis[x] = 1; dep[x] = d; for (int i = first[x]; ~i; i = next[i]) if (!vis[a[i].y]) dfs(a[i].y, d+1); } inline void fuck() {rep(j, 1, M) rep(i, 1, n) fa[i][j] = fa[fa[i][j-1]][j-1];}//求i节点2^j祖先 inline int LCA(int u, int v) { if (dep[u] < dep[v]) swap(u, v);//保证depth(u) >= depth(v) int deep = dep[u] - dep[v]; rep(i, 0, M) if ((1 << i) & deep) u = fa[u][i];//使u,v为同一层节点 if (u == v) return u; REP(i, M, 0) if (fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];//倍增 return fa[u][0]; } int main() { cin >> T_T; while (T_T--) { N = -1; memset(fa, 0, sizeof(fa)); memset(first, -1, sizeof(first)); memset(next, -1, sizeof(next)); memset(dep, 0, sizeof(dep)); cin >> n; int u, v; rep(i, 1, n-1) { scanf("%d%d", &u, &v); fa[v][0] = u;//v的父节点为u if (!fa[u][0]) root = u; add(u, v), add(v, u); } memset(vis, 0, sizeof(vis)); dfs(root, 1); fuck(); scanf("%d%d", &u, &v); printf("%d\n", LCA(u, v)); } return 0; }</span>