Advertisement
ivnikkk

Untitled

Jun 21st, 2022
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #define debug(tl) cerr<<#tl<<' '<<tl<<'\n';
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5. #define all(d) d.begin(), d.end()
  6. typedef long long ll;
  7. typedef pair<ll, ll> pll;
  8. typedef pair<int, int> pii;
  9. typedef long double ld;
  10. const int N = 2000;
  11. int p[N];
  12. void init(int n) {
  13.     fill(p, p + n, -1);
  14. }
  15. int find(int x) {
  16.     return p[x] < 0 ? x : p[x] = find(p[x]);
  17. }
  18. bool join(int a, int b) {
  19.     a = find(a), b = find(b);
  20.     if (a == b)
  21.         return false;
  22.     if (p[a] > p[b])
  23.         swap(a, b);
  24.     p[a] += p[b];
  25.     p[b] = a;
  26.     return true;
  27. }
  28. signed main() {
  29. #ifdef _DEBUG
  30.     freopen("input.txt", "r", stdin);
  31.     freopen("output.txt", "w", stdout);
  32. #endif
  33.     ios_base::sync_with_stdio(false);
  34.     cin.tie(nullptr);
  35.     cout.tie(nullptr);
  36.     int n;
  37.     cin >> n;
  38.     struct edge {
  39.         int u, v, w;
  40.         bool operator<(const edge &other) {
  41.             return w < other.w;
  42.         }
  43.     };
  44.     vector<edge> e;
  45.     for (int i = 0; i < n; i++) {
  46.         for (int j = 0; j < n; j++) {
  47.             int x;cin >> x;
  48.             if (x)e.push_back({ i,j, x });
  49.         }
  50.     }
  51.     sort(all(e));
  52.     init(n);
  53.     vector<edge> ans;
  54.     for (int i = 0; i < (int)e.size(); i++) {
  55.         if (join(e[i].u, e[i].v)) {
  56.             ans.emplace_back(e[i]);
  57.             if ((int)ans.size() == n - 1)break;
  58.         }
  59.     }
  60.     cout << n << '\n';
  61.     for (const edge& i : ans) {
  62.         cout << i.u + 1 << ' ' << i.v + 1 << ' ' << i.w << '\n';
  63.     }
  64. }
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement