Advertisement
tien_noob

LCA + DSF - TrainingK54

Jun 9th, 2021
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. //Make CSP great again
  2. #include <bits/stdc++.h>
  3. #define TASK "TESTCODE"
  4. using namespace std;
  5. const int N = 1e5;
  6. int lab[N + 1], p[N + 1], n, m;
  7. vector<int> Query[2];
  8. int FindSet(int u)
  9. {
  10.     if (lab[u] < 0)
  11.     {
  12.         return u;
  13.     }
  14.     return lab[u] = FindSet(lab[u]);
  15. }
  16. void read()
  17. {
  18.    memset(lab, -1, sizeof(lab));
  19.    cin >> n >> m;
  20.    Query[0].push_back(0);
  21.    Query[1].push_back(0);
  22. }
  23. bool check(int a, int num)
  24. {
  25.     int u = Query[0][num], v = Query[1][num];
  26.     while (true)
  27.     {
  28.         if (u == a)
  29.         {
  30.             return true;
  31.         }
  32.         if (u == v)
  33.         {
  34.             return false;
  35.         }
  36.         u = p[u];
  37.     }
  38. }
  39. void solve()
  40. {
  41.    for (int i = 1; i <= m; ++ i)
  42.    {
  43.        int type;
  44.        cin >> type;
  45.        if (type == 1)
  46.        {
  47.            int u, v;
  48.            cin >> u >> v;
  49.            lab[u] = v;
  50.            p[u] = v;
  51.        }
  52.        if (type == 2)
  53.        {
  54.            int u; cin >> u;
  55.            Query[0].push_back(u);
  56.            Query[1].push_back(FindSet(u));
  57.        }
  58.        if (type == 3)
  59.        {
  60.            int a, num;
  61.            cin >> a >> num;
  62.            if (check(a, num))
  63.            {
  64.                cout << "YES";
  65.            }
  66.            else
  67.            {
  68.                cout << "NO";
  69.            }
  70.            cout << '\n';
  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.         //cout << "Case " << __ << ": ";
  89.         read();
  90.         solve();
  91.     }
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement