Advertisement
Korotkodul

Problem C. Острова

Oct 6th, 2021
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <set>
  2. #include <cmath>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <iostream>
  6. using namespace std;
  7.  
  8.  
  9.  
  10. int get_parent(int v, vector <int>& parent, int& father, vector <int>& sz) {
  11.     if (parent[v] == v) {
  12.         father = v;
  13.         return v;
  14.     }
  15.     return get_parent(parent[v], parent, father, sz);
  16.     parent[v] = father;
  17. }
  18.  
  19. void unite(int fr, int to, vector <int>& parent, vector <int>& sz, int& max_sz) {
  20.     int fath_1 = -1;
  21.     int dad_1 = get_parent(fr, parent, fath_1, sz);
  22.     int fath_2 = -2;
  23.     int dad_2 = get_parent(to, parent, fath_2, sz);
  24.     if (dad_1 == dad_2) {
  25.         return;
  26.     }
  27.     else if (sz[dad_1] <= sz[dad_2]) {
  28.         parent[dad_1] = dad_2;
  29.         sz[dad_2] += sz[dad_1];
  30.         if (sz[dad_2] > max_sz) {
  31.             max_sz = sz[dad_2];
  32.         }
  33.     }
  34.     else {
  35.         parent[dad_2] = dad_1;
  36.         sz[dad_1] += sz[dad_2];
  37.         if (sz[dad_1] > max_sz) {
  38.             max_sz = sz[dad_1];
  39.         }
  40.     }
  41. }
  42.  
  43.  
  44. int main()
  45. {
  46.     ios_base::sync_with_stdio(false);
  47.     cin.tie(0);
  48.     int n, m;
  49.     cin >> n >> m;
  50.     vector <int> parent(n + 1);
  51.     for (int i = 1; i < n + 1; ++i) {
  52.         parent[i] = i;
  53.     }
  54.     vector <int> sz(n + 1, 1); //размеры компонент связности -- сколько вершин
  55.     int ans = 0;
  56.     int max_sz = 1;
  57.     for (int i = 0;i<m;++i){
  58.         if (max_sz == n) {
  59.             ans = i;
  60.             break;
  61.         }
  62.         int a, b;
  63.         cin >> a >> b;
  64.         unite(a, b, parent, sz, max_sz);
  65.         /*cout << "parent\n";
  66.         for (auto x : parent) cout << x << ' ';
  67.         cout << '\n';
  68.         cout << "size\n";
  69.         for (auto x : sz) cout << x << ' ';
  70.         cout << '\n';
  71.         cout << '\n';*/
  72.     }
  73. cout << ans << '\n';
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement