Advertisement
Guest User

Untitled

a guest
Sep 28th, 2014
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. const int maxn = 100000;
  6.  
  7. int dsu[maxn*2], rank[maxn*2];
  8.  
  9. void dsu_init(int n)
  10. {
  11.     for (int i = 0; i < 2*n; i++)
  12.     {
  13.         dsu[i] = i;
  14.         rank[i] = 0;
  15.     }
  16. }
  17.  
  18. int dsu_find(int a)
  19. {
  20.     if (dsu[a] == a) return a;
  21.     return dsu[a] = dsu_find(dsu[a]);
  22. }
  23.  
  24. bool _dsu_unite(int a, int b)
  25. {
  26.     a = dsu_find(a);
  27.     b = dsu_find(b);
  28.     if (a == b) return 1;
  29.     if ((a^1) == b) return 0;
  30.     if (rank[a] < rank[b])
  31.     {
  32.         dsu[a] = b;
  33.     }
  34.     else if(rank[a] > rank[b])
  35.     {
  36.         dsu[b] = a;
  37.     }
  38.     else
  39.     {
  40.         dsu[a] = b;
  41.         rank[b]++;
  42.     }
  43.     return 1;
  44. }
  45.  
  46. bool dsu_unite_different(int a, int b)
  47. {
  48.     a = dsu_find(2*a);
  49.     b = dsu_find(2*b);
  50.     return _dsu_unite(a, b^1) && _dsu_unite(a^1, b);
  51. }
  52.  
  53. bool dsu_unite_same(int a, int b)
  54. {
  55.     a = dsu_find(2*a);
  56.     b = dsu_find(2*b);
  57.     return _dsu_unite(a, b) && _dsu_unite(a^1, b^1);
  58. }
  59.  
  60. void dsu_write_example(int n)
  61. {
  62.     cout << "First: ";
  63.     for (int i = 0; i < 2*n; i+=2)
  64.     {
  65.         if (dsu_find(i)&1)
  66.         {
  67.             cout << i/2+1 << " ";
  68.         }
  69.     }
  70.     cout << endl << "Second: ";
  71.     for (int i = 0; i < 2*n; i+=2)
  72.     {
  73.         if (!(dsu_find(i)&1))
  74.         {
  75.             cout << i/2+1 << " ";
  76.         }
  77.     }
  78.     cout << endl;
  79. }
  80.  
  81. int main()
  82. {
  83.     ios_base::sync_with_stdio(0);
  84.     int n, m, a, b;
  85.     char c;
  86.     cin >> n >> m;
  87.     dsu_init(n);
  88.     for (int i = 0; i < m; i++)
  89.     {
  90.         cin >> c;
  91.         if (c == 's')
  92.         {
  93.             cin >> a >> b;
  94.             if (!dsu_unite_same(a-1, b-1))
  95.             {
  96.                 cout << "ERROR";
  97.                 return 0;
  98.             }
  99.         }
  100.         else if (c == 'd')
  101.         {
  102.             cin >> a >> b;
  103.             if(!dsu_unite_different(a-1, b-1))
  104.             {
  105.                 cout << "ERROR";
  106.                 return 0;
  107.             }
  108.         }
  109.         else
  110.         {
  111.             dsu_write_example(n);
  112.         }
  113.     }
  114.     return 0;
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement