fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. const int N = 2e5 + 5;
  12. const int LOG = 18;
  13.  
  14. int n, q;
  15. vector<int> adj[N];
  16.  
  17. int up[LOG][N];
  18. int tin[N], tout[N], timer;
  19. int depth[N]; // depth[u] = Độ sâu của đỉnh u
  20.  
  21. void dfs(int u, int p) {
  22. tin[u] = ++timer;
  23. up[0][u] = p;
  24. for (int i = 1; i < LOG; i++) {
  25. up[i][u] = up[i - 1][up[i - 1][u]];
  26. }
  27. for (int v : adj[u]) {
  28. if (v == p) continue;
  29. depth[v] = depth[u] + 1;
  30. dfs(v, u);
  31. }
  32. tout[u] = timer;
  33. }
  34.  
  35. bool isAncestor(int u, int v) {
  36. return (tin[u] <= tin[v] && tout[v] <= tout[u]);
  37. }
  38.  
  39. int lca(int u, int v) {
  40. if (isAncestor(u, v)) return u;
  41. if (isAncestor(v, u)) return v;
  42. for (int i = LOG - 1; i >= 0; i--) {
  43. if (!isAncestor(up[i][u], v)) {
  44. u = up[i][u];
  45. }
  46. }
  47. return up[0][u];
  48. }
  49.  
  50. int main() {
  51. ios::sync_with_stdio(false);
  52. cin.tie(nullptr);
  53. cin >> n >> q;
  54.  
  55. for (int i = 0; i < n - 1; i++) {
  56. int u, v;
  57. cin >> u >> v;
  58. adj[u].push_back(v);
  59. adj[v].push_back(u);
  60. }
  61.  
  62. timer = 0;
  63. depth[1] = 0;
  64. dfs(1, 1);
  65.  
  66. while (q--) {
  67. int u, v;
  68. cin >> u >> v;
  69. int dist = depth[u] + depth[v] - 2 * depth[lca(u, v)];
  70. cout << dist << '\n';
  71. }
  72. }
Success #stdin #stdout 0.01s 22864KB
stdin
5 3
1 2
1 3
3 4
3 5
1 3
2 5
1 4
stdout
1
3
2