1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
using namespace std; enum{MAXN = 500005}; int node_number, question, root,cnt; int last[MAXN], fa[MAXN][22], Dep[MAXN]; struct Edge { int to, next; }; Edge edge[2 * MAXN]; void dfs(int x, int father) { int i, k, y; fa[x][0] = father; Dep[x] = Dep[father] + 1; k = ceil(log(Dep[x]) / log(2)); for (i = 1; i <= k; i++) { fa[x][i] = fa[fa[x][i - 1]][i - 1]; } y = last[x]; for (i = last[x]; i; i = edge[i].next) { if (edge[i].to != father) { dfs(edge[i].to, x); } } } void add_edge(int x, int y) { cnt++; edge[cnt].to = y; edge[cnt].next = last[x]; last[x] = cnt; } int LCA(int x, int y) { int i, k, s; s = ceil(log(node_number) / log(2)); if (Dep[x] < Dep[y]) { swap(x, y); } k = Dep[x] - Dep[y]; for (i = 0; i <= s; i++) { if (k & (1 << i)) { x = fa[x][i]; } } if (x == y) { return x; } s = ceil(log(Dep[x]) / log(2)); for (i = s; i >= 0; i--) { if (fa[x][i] != fa[y][i]) { x = fa[x][i]; y = fa[y][i]; } } return fa[x][0]; } int main() { int i, x, y; //cin >> node_number >> question >> root; scanf("%d%d%d", &node_number, &question, &root); for (i = 1; i <= node_number-1; i++) { //cin >> x >> y; scanf("%d%d", &x, &y); add_edge(x, y); add_edge(y, x); } dfs(root, 0); for (int i = 1; i <= question; i++) { //cin >> x >> y; scanf("%d%d", &x, &y); //cout << LCA(x, y) << endl; printf("%d\n", LCA(x, y)); } return 0; }
|