The first LCA question ~~~
...
# Include <string. h >#include <algorithm> # include <iostream> # include <cmath> # include <cstdio> # include <vector> # define n 10005 using namespace STD; int lev[ 2 * n], first [N], visit [2 * n]; int head [N]; typedef struct STR {int to; int next;} node; node node [N]; int dpmin [15] [2 * n]; int in [N]; int tot, Res; void Init () {memset (first,-1, sizeof (first); memset (in, 0, sizeof (in); memset (Head,-1, sizeof (head); Tot = 1; Res = 1 ;} void add (int, Int B) {node [res]. to = B; node [res]. next = head [a]; head [a] = res ++;} void rmq (INT num) {for (INT I = 1; I <= num; ++ I) dpmin [0] [I] = lev[ I]; for (INT I = 1; (1 <I) <= num; ++ I) for (Int J = 1; j + (1 <I)-1 <= num; ++ J) dpmin [I] [J] = min (dpmin [I-1] [J], dpmin [I-1] [J + (1 <(I-1)]);} int doit (INT Sx, int ex) {int K = (INT) (log (ex-SX + 1.0)/log (2.0 )); int temp = min (dpmin [k] [SX], dpmin [k] [ex-(1 <k) + 1]); For (INT I = SX; I <= ex; ++ I) if (lev[ I] = temp) return visit [I];} void DFS (INT cur, int now) // Deep Search traversal {If (first [now] =-1) first [now] = tot; visit [tot] = now; lev_[ tot ++] = cur; If (head [now] =-1) return; For (INT I = head [now]; i! =-1; I = node [I]. next) {DFS (cur + 1, node [I]. to); visit [tot] = now; lev[ tot ++] = cur ;}} int main () {int t; scanf ("% d", & T ); while (t --) {int N, I; scanf ("% d", & N); Init (); for (I = 1; I <n; ++ I) {int A, B; scanf ("% d", & A, & B); add (a, B); in [B] ++ ;} for (I = 1; in [I]; ++ I); DFS (0, I); rmq (2 * N-1); int A, B; scanf ("% d", & A, & B); A = first [a], B = first [B]; // find the position where A and B appear for the first time if (A> B) Swap (a, B); printf ("% d \ n", doit (, b);} return 0;} // in records the node's inbound level. frist records the location where the node appears for the first time, visit records the access sequence of nodes (including backtracing) // the speed of the log records the depth of the corresponding node.
Please see http://blog.csdn.net/smallacmer/article/details/7432664