Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <cctype>
  2. #include <climits>
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <algorithm>
  9. #include <bitset>
  10. #include <deque>
  11. #include <fstream>
  12. #include <iomanip>
  13. #include <iostream>
  14. #include <list>
  15. #include <map>
  16. #include <queue>
  17. #include <set>
  18. #include <stack>
  19. #include <vector>
  20.  
  21. #define x first
  22. #define y second
  23.  
  24. using namespace std;
  25.  
  26. typedef long long ll;
  27. typedef pair<int, int> pii;
  28. typedef vector<int> lnum;
  29. const int MAXN = (int)1e7 + 10;
  30.  
  31. int n, l;
  32. vector <int> g[500010];
  33. vector <pii> q;
  34. vector<int> tin, tout;
  35. int timer;
  36. vector < vector<int> > up;
  37.  
  38. void dfs (int v, int p = 0) {
  39. tin[v] = ++timer;
  40. up[v][0] = p;
  41. for (int i=1; i<=l; ++i)
  42. up[v][i] = up[up[v][i-1]][i-1];
  43. for (size_t i=0; i<g[v].size(); ++i) {
  44. int to = g[v][i];
  45. if (to != p)
  46. dfs (to, v);
  47. }
  48. tout[v] = ++timer;
  49. }
  50.  
  51. bool upper (int a, int b) {
  52. return tin[a] <= tin[b] && tout[a] >= tout[b];
  53. }
  54.  
  55. int lca (int a, int b) {
  56. if (upper (a, b)) return a;
  57. if (upper (b, a)) return b;
  58. for (int i=l; i>=0; --i)
  59. if (! upper (up[a][i], b))
  60. a = up[a][i];
  61. return up[a][0];
  62. }
  63.  
  64. int main() {
  65. int n;
  66. cin >> n;
  67. for (int i = 0; i < n; i++){
  68. string s;
  69. int x, y;
  70. cin >> s >> x >> y;
  71. x--;y--;
  72. if (s == "ADD"){
  73. g[x].push_back(y);
  74. g[y].push_back(x);
  75. } else{
  76. q.push_back(make_pair(x, y));
  77. }
  78. }
  79. tin.resize (n), tout.resize (n), up.resize (n);
  80. l = 1;
  81. while ((1<<l) <= n) ++l;
  82. for (int i=0; i<n; ++i) up[i].resize (l+1);
  83. for (int i = 0; i < n; i++)
  84. if (g[i].size() > 0){
  85. dfs(i);
  86. break;
  87. }
  88.  
  89. for (int i = 0; i < q.size(); i++) {
  90. int a = q[i].x, b = q[i].y; // текущий запрос
  91. int res = lca (a, b); // ответ на запрос
  92. cout << res + 1 << endl;
  93. }
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement