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 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include<iostream> #include<stdio.h> #include<vector> #include<algorithm> #include<string.h> using namespace std; typedef long long LL; const int MAXN = 100000 + 5; vector<int>v[MAXN]; int num[MAXN]; int pre[MAXN]; int pos[MAXN]; vector<int>euler; int vis[MAXN]; int tot; int tre[MAXN * 8];
void dfs(int t) { num[t] = ++tot; pre[num[t]] = t; euler.push_back(num[t]); vis[t] = 1; pos[num[t]] = euler.size() - 1; for (int i = 0; i < v[t].size(); i++) { if (vis[v[t][i]] == 0) { dfs(v[t][i]); euler.push_back(num[t]); } } } void build(int t, int l, int r) { if (l == r) { tre[t] = euler[l]; return; } int mid = l + r >> 1; build(t << 1, l, mid); build(t << 1 | 1, mid + 1, r); tre[t] = min(tre[t << 1], tre[t << 1 | 1]); } int ans; void query(int t, int l, int r, int x, int y) { if (l >= x && r <= y) { ans = min(ans, tre[t]); return; } int mid = l + r >> 1; if (y <= mid) { query(t << 1, l, mid, x, y); } else if (x > mid) { query(t << 1 | 1, mid + 1, r, x, y); } else { query(t << 1, l, mid, x, y); query(t << 1 | 1, mid + 1, r, x, y); } } int main() { tot = 0; ans = 99999999; memset(num, 0, sizeof(num)); memset(pos, 0, sizeof(pos)); euler.clear(); euler.push_back(0); for (int i = 0; i < MAXN; i++) { v[i].clear(); } int n, m; scanf("%d%d", &n, &m); for (int i = 1; i < n; i++) { int a, b; scanf("%d%d", &a, &b); v[a].push_back(b); v[b].push_back(a); } int root = 1; dfs(root); build(1, 1, euler.size() - 1); for (int i = 0; i < m; i++) { int U, V; scanf("%d%d", &U, &V); U = pos[num[U]]; V = pos[num[V]]; if (U > V) swap(U, V); query(1, 1, euler.size() - 1, U, V); printf("%d\n", pre[ans]); } }
|