fork(1) download
  1. #include <bits/stdc++.h>
  2. #include <ext/pb_ds/assoc_container.hpp> // Common file
  3. #include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
  4. #include <ext/pb_ds/detail/standard_policies.hpp>
  5. #define INF 2000'000'000
  6. #define MOD 1000'000'007
  7. using namespace std;
  8. using namespace __gnu_pbds;
  9.  
  10. typedef long long ll;
  11. typedef unsigned long long ull;
  12. typedef long double ld;
  13. typedef tree<int, null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
  14.  
  15. int n;
  16. int anc[300'005][22];
  17. int dep[300'005];
  18.  
  19. vector<int> adj[300'005];
  20.  
  21. void build_anc(int v, int par = 0, int d = 0){
  22. anc[v][0] = par, dep[v] = d;
  23. for(int p = 1; p < 22; p++){
  24. anc[v][p] = anc[ anc[v][p-1] ][p-1];
  25. }
  26.  
  27. for(int u : adj[v]){
  28. if(u != par)
  29. build_anc(u, v, d+1);
  30. }
  31. }
  32.  
  33. int kth_anc(int v, int k){// O(cnt_bits)
  34. while(k){
  35. int lsb = k & -k;
  36. int idx = __builtin_ctz(lsb);
  37. v = anc[v][idx];
  38. k -= lsb;
  39. }
  40. return v;
  41. }
  42.  
  43. int lca(int a, int b){
  44. if(dep[a] < dep[b])
  45. swap(a, b);
  46. a = kth_anc(a, dep[a] - dep[b]);
  47. if(a == b)
  48. return a;
  49.  
  50. for(int bit = 21; bit >= 0; bit--){
  51. if( anc[a][bit] != anc[b][bit])
  52. a = anc[a][bit], b = anc[b][bit];
  53. }
  54. // they should be exactly the children of the lca
  55. return anc[a][0];
  56. }
  57.  
  58. int main(){
  59. ios_base::sync_with_stdio(false);
  60. cin.tie(NULL), cout.tie(NULL);
  61. //freopen("in", "r", stdin);//freopen("out", "w", stdout);
  62. cin >> n;
  63. for(int i = 1,u,v; i < n && cin >> u >> v; i++){
  64. adj[u].push_back(v), adj[v].push_back(u);
  65. }
  66. build_anc(1);
  67. int q;
  68. cin >> q;
  69. for(int a,b,c; q-- && cin >> a >> b >> c; ){
  70. int l = lca(a,b);
  71. int path = dep[a] + dep[b] - dep[l] * 2;
  72. if(c >= path){
  73. cout << b << "\n";
  74. }
  75. else if(c <= dep[a] - dep[l]){
  76. cout << kth_anc(a, c) << "\n";
  77. }
  78. else{
  79. c -= dep[a] - dep[l];
  80. cout << kth_anc(b, dep[b] - dep[l] - c) << "\n";
  81. }
  82. }
  83. return 0;
  84. }
Success #stdin #stdout 0s 10744KB
stdin
Standard input is empty
stdout
Standard output is empty