Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <set>
- #include <cmath>
- #include <vector>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- int get_parent(int v, vector <int>& parent, int& father, vector <int>& sz) {
- if (parent[v] == v) {
- father = v;
- return v;
- }
- return get_parent(parent[v], parent, father, sz);
- parent[v] = father;
- }
- void unite(int fr, int to, vector <int>& parent, vector <int>& sz, int& max_sz) {
- int fath_1 = -1;
- int dad_1 = get_parent(fr, parent, fath_1, sz);
- int fath_2 = -2;
- int dad_2 = get_parent(to, parent, fath_2, sz);
- if (dad_1 == dad_2) {
- return;
- }
- else if (sz[dad_1] <= sz[dad_2]) {
- parent[dad_1] = dad_2;
- sz[dad_2] += sz[dad_1];
- if (sz[dad_2] > max_sz) {
- max_sz = sz[dad_2];
- }
- }
- else {
- parent[dad_2] = dad_1;
- sz[dad_1] += sz[dad_2];
- if (sz[dad_1] > max_sz) {
- max_sz = sz[dad_1];
- }
- }
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- int n, m;
- cin >> n >> m;
- vector <int> parent(n + 1);
- for (int i = 1; i < n + 1; ++i) {
- parent[i] = i;
- }
- vector <int> sz(n + 1, 1); //размеры компонент связности -- сколько вершин
- int ans = 0;
- int max_sz = 1;
- for (int i = 0;i<m;++i){
- if (max_sz == n) {
- ans = i;
- break;
- }
- int a, b;
- cin >> a >> b;
- unite(a, b, parent, sz, max_sz);
- /*cout << "parent\n";
- for (auto x : parent) cout << x << ' ';
- cout << '\n';
- cout << "size\n";
- for (auto x : sz) cout << x << ' ';
- cout << '\n';
- cout << '\n';*/
- }
- cout << ans << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement