Test instructions: to seek LCA ... This tree is a one-way side, with an entry level of 0 for the root and only a set of queries.
Solution: St For LCA (only this). DP[I][J] indicates who the first 2j ancestor of the first point, the transfer equation dp[i][j] = dp[dp[i][j-1]][j-1]. DFS one side record dp[i][0], and the depth of the point, the time of the LCA to the depth of the point to the same depth, if at this time two points coincident that the LCA is the current point, or else rise at the same time, their father is the LCA.
Code:
#include <stdio.h> #include <iostream> #include <algorithm> #include <string> #include < string.h> #include <math.h> #include <limits.h> #include <time.h> #include <stdlib.h># include<map> #include <queue> #include <set> #include <stack> #include <vector> #define LL Long longusing namespace Std;int n;vector <int> edge[10005];int indegree[10005];int dp[10005][16];int deep[10005] ; void Dfs (int root, int d) {deep[root] = D; int len = Edge[root].size (); for (int i = 0; i < len; i++) {dp[edge[root][i]][0] = root; DFS (Edge[root][i], D + 1); }}void build (int root) {memset (DP, 0, sizeof DP); memset (deep, 0, sizeof deep); DFS (root, 0); Dp[root][0] = root; for (int j = 1; J <, J + +) for (int i = 1; I <= n; i++) dp[i][j] = dp[dp[i][j-1]][j-1];} int LCA (int a, int b) {if (Deep[a] > Deep[b]) swap (A, b); for (int i = +; I >= 0; i--) if (Deep[dp[b][i]] >= Deep[a]) b = dp[b][i]; if (a = = B) return A; for (int i = +; I >= 0; i--) {if (Dp[a][i]! = Dp[b][i]) {a = Dp[a][i]; b = Dp[b][i]; }} return dp[a][0];} int main () {int T; while (~SCANF ("%d", &t)) {while (t--) {memset (indegree, 0, sizeof indegree); for (int i = 0; i < 10005; i++) edge[i].clear (); scanf ("%d", &n); for (int i = 0; i < n-1; i++) {int A, B; scanf ("%d%d", &a, &b); Edge[a].push_back (b); indegree[b]++; } int root; for (int i = 1; I <= n; i++) if (indegree[i] = = 0) {root = i; Break } build (root); int A, B; scanf ("%d%d", &a, &b); printf ("%d\n", LCA (A, b)); } } return 0;}
POJ 1330 Nearest Common Ancestors