Josif_tepe

Untitled

May 10th, 2026
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6. const int maxn = 50005;
  7. int idx[maxn];
  8. int d[maxn];
  9.  
  10. void init(int n) {
  11.     for(int i = 0; i <= n; i++) {
  12.         idx[i] = i;
  13.         d[i] = 0;
  14.     }
  15. }
  16. int root(int x) {
  17.     if(x == idx[x]) {
  18.         return x;
  19.     }
  20.     int parent = idx[x];
  21.     idx[x] = root(idx[x]);
  22.     d[x] += d[parent];
  23.     return idx[parent];
  24. }
  25.  
  26. bool unite(int x, int y, int type, int n) {
  27.     if(x >= n or y >= n) {
  28.         return true;
  29.     }
  30.     int root_x = root(x);
  31.     int root_y = root(y);
  32.    
  33.     int value = ((d[x] - d[y] - type) % 3 + 3) % 3;
  34.     if(root_x == root_y) {
  35.         if(value != 0) {
  36.             return true;
  37.         }
  38.         return false;
  39.     }
  40.     else {
  41.         idx[root_x] = root_y;
  42.         d[root_x] = 3 - value;
  43.         return false;
  44.     }
  45. }
  46. int main(){
  47.     ios_base::sync_with_stdio(false);
  48.     int T;
  49.     cin >> T;
  50.    
  51.     while(T--) {
  52.         int n, k;
  53.         cin >> n >> k;
  54.         int res = 0;
  55.         init(n);
  56.         for(int i = 0; i < k; i++) {
  57.             int type, x, y;
  58.             cin >> type >> x >> y;
  59.             x--; y--; type--;
  60.            
  61.             res += unite(x, y, type, n);
  62.            
  63.         }
  64.         cout << res << "\n";
  65.     }
  66.     return 0;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment