Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
LCA ----> RMQ#include <stdio.h> #include <stdlib.h> //#include <math.h> #include <algorithm> using namespace std; #define MAX_N 10001 #define MAX_M 20001 struct node { int t, next; node (int _t = 0, int _next = -1) { t = _t, next = _next; } }; node tree[MAX_N]; int tf[MAX_N]; int f[MAX_M][17], logn[MAX_M];// logn[i]: log (2, i) int first[MAX_N]; int ord[MAX_M], dep[MAX_M]; int t, n, num, root; inline void add(int p, int a, int b) { tree[p] = node (b, tf[a]); tf[a] = p; } int find_root(void) { for (int i = 1; i <= n; i++) if (ord[i] == 0) return i; } void dfs(int v, int deep) { ord[++num] = v, dep[num] = deep; if (!first[v]) first[v] = num; for (int i = tf[v]; i != -1; i = tree[i].next) { dfs (tree[i].t, deep + 1); ord[++num] = v, dep[num] = deep; } } void RMQ_LCA(void) { logn[0] = -1; for (int i = 1; i <= num; i++) f[i][0] = i; for (int j = 1, s = 1; s <= num; s <<= 1, j++) { for (int i = 1; i + s<= num; i++) { if (dep[f[i][j - 1]] < dep[f[i + s][j - 1]]) f[i][j] = f[i][j - 1]; else f[i][j] = f[i + s][j - 1]; } } } int LCA(int a, int b) { if (a > b) swap (a, b); int k = logn[b - a + 1], s = 1 << k; if (dep[f[a][k]] < dep[f[b - s + 1][k]]) return ord[f[a][k]]; else return ord[f[b - s + 1][k]]; } int main(void) { scanf("%d", &t); logn[0] = -1; for (int i = 1; i < MAX_M; i++) logn[i] = (i & (i - 1)) ? logn[i - 1]: logn[i - 1] + 1; for (int i = 1, a, b; i <= t; i++) { scanf ("%d",&n); memset (tf, -1, sizeof (tf)); memset (ord, 0, sizeof (ord)); memset (first, 0, sizeof (first)); for (int j = 1; j < n; j++) { scanf ("%d%d", &a, &b); add (j, a, b); ord[b] = a; // 暂时记录b的父亲节点 } root = find_root (); num = 0; dfs (root, 1); RMQ_LCA (); scanf ("%d%d", &a, &b); printf ("%d\n", LCA (first[a], first[b])); } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator