tien_noob

Graph + Disjoint Set Forest

May 13th, 2021 (edited)
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define TASK "LABYRINTH"
  3. using namespace std;
  4. const int N = 1e5;
  5. bool unlocked[N + 1];
  6. vector<int> Adj[N+1];
  7. int n, m, k, x, y, Trace[N + 1];
  8. char type;
  9. void read()
  10. {
  11.    cin >> n >> m >> k;
  12.    fill(unlocked, unlocked + n + 1, false);
  13.    fill(Trace, Trace + n + 1, -1);
  14.    for (int i = 1; i <= m; ++ i)
  15.    {
  16.        cin >> x >> y;
  17.        Adj[x].push_back(y);
  18.        Adj[y].push_back(x);
  19.    }
  20. }
  21. int FindSet(int u)
  22. {
  23.     if (Trace[u] < 0)
  24.     {
  25.         return u;
  26.     }
  27.     return Trace[u] = FindSet(Trace[u]);
  28. }
  29. void Unite(int r, int s)
  30. {
  31.     if (Trace[s] < Trace[r])
  32.     {
  33.         swap(r, s);
  34.     }
  35.     Trace[r] += Trace[s];
  36.     Trace[s] = r;
  37. }
  38. void solve()
  39. {
  40.    while (k--)
  41.    {
  42.        cin >> type;
  43.        if (type == 'X')
  44.        {
  45.            cin >> x;
  46.            unlocked[x] = true;
  47.            for (int v : Adj[x])
  48.            {
  49.                if (unlocked[v])
  50.                {
  51.                    int r = FindSet(x), s = FindSet(v);
  52.                    if (r != s)
  53.                    {
  54.                        Unite(r, s);
  55.                    }
  56.                }
  57.            }
  58.        }
  59.        else
  60.        {
  61.            cin >> x >> y;
  62.            int u = FindSet(x), v = FindSet(y);
  63.            if (u == v)
  64.            {
  65.                cout << "Y";
  66.            }
  67.            else
  68.            {
  69.                cout << "N";
  70.            }
  71.        }
  72.    }
  73. }
  74. int main()
  75. {
  76.    ios_base::sync_with_stdio(false);
  77.    cin.tie(nullptr);
  78.    freopen(TASK".INP", "r", stdin);
  79.    freopen(TASK".OUT", "w", stdout);
  80.    int t = 1;
  81.    bool typetest = false;
  82.    if (typetest)
  83.    {
  84.       cin >> t;
  85.    }
  86.    for (int __ = 1; __ <= t; ++ __)
  87.    {
  88.       read();
  89.       solve();
  90.    }
  91. }
  92.  
Add Comment
Please, Sign In to add comment