Advertisement
Vince14

/<> 10838 (LCA w/out binary jumping)

Sep 29th, 2023
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <vector>
  7. #include <set>
  8. #include <map>
  9. #include <stack>
  10. #include <queue>
  11. #include <deque>
  12. #include <unordered_map>
  13. #include <numeric>
  14. #include <iomanip>
  15. using namespace std;
  16. #define pii pair<int , int>
  17. #define ll long long
  18. #define FAST ios_base::sync_with_stdio(false); cin.tie(NULL)
  19. const long long dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
  20. const long long dl[2] = {1, -1};
  21. const long long MOD = 1000000007;
  22. const long long MAXN = 100005;
  23.  
  24. int N, K;
  25. int par[MAXN];
  26. int color[MAXN];
  27. int depth[MAXN];
  28. int visited[MAXN];
  29.  
  30. int LCA(int x, int y, int k){
  31.     for(int i = 0; i < 1005; i++){
  32.         visited[x] = k;
  33.         if(x == 0) {
  34.             break;
  35.         }
  36.         x = par[x];
  37.     }
  38.     for(int i = 0; i < 1005; i++){
  39.         if(visited[y] == k or y == 0){
  40.             return y;
  41.         }
  42.         y = par[y];
  43.     }
  44.     return y;
  45. }
  46.  
  47. int main() {
  48.     FAST;
  49.     cin >> N >> K;
  50.     memset(depth, 2, sizeof(depth));
  51.     depth[0] = 1;
  52.     for(int r, x, y, z, k = 1; k <= K; k++){
  53.         cin >> r;
  54.         if(r == 1){
  55.             cin >> x >> y >> z;
  56.             int lca = LCA(x, y, k);
  57.             while(x != lca){
  58.                 color[x] = z;
  59.                 x = par[x];
  60.             }
  61.             while(y != lca){
  62.                 color[y] = z;
  63.                 y = par[y];
  64.             }
  65.         }
  66.         else if(r == 2){
  67.             cin >> x >> y;
  68.             par[x] = y;
  69.         }
  70.         else{
  71.             cin >> x >> y;
  72.             int lca = LCA(x, y, k);
  73.             set<int> colors;
  74.             while(x != lca){
  75.                 colors.insert(color[x]);
  76.                 x = par[x];
  77.             }
  78.             while(y != lca){
  79.                 colors.insert(color[y]);
  80.                 y = par[y];
  81.             }
  82.             cout << colors.size() << "\n";
  83.         }
  84.     }
  85. }
  86.  
  87. /*
  88. 6 8
  89. 2 1 3
  90. 2 5 3
  91. 1 5 4 8
  92. 3 4 5
  93. 2 3 4
  94. 1 0 3 7
  95. 3 2 5
  96. 3 4 2
  97.  */
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement