Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- class DSU
- {
- public:
- vector<int> parent;
- DSU(int N)
- {
- parent.resize(N, -1);
- }
- int find(int v)
- {
- int r = v;
- while (parent[r] != -1)
- {
- r = parent[r];
- }
- while (parent[v] != -1)
- {
- int tmp = v;
- v= parent[v];
- parent[tmp] = r;
- }
- return r;
- }
- void unio (int i, int j)
- {
- int ri = find(i);
- int rj = find(j);
- parent[ri] = rj;
- }
- };
- int main()
- {
- int N = 0, M = 0;
- cin >> N >> M;
- DSU dsu(N + 1);
- int from = 0, to = 0, cnt = 0;
- for (int i = 0; i < M; i++)
- {
- cin >> from >> to;
- cnt++;
- if (dsu.find(from) != dsu.find(to))
- {
- dsu.unio (from, to);
- N--;
- }
- if (N == 1)
- break;
- }
- cout << cnt;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement