Alex_tz307

Kruskal

Sep 11th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define nmax 400005
  3.  
  4. using namespace std;
  5.  
  6. ifstream fin ("apm.in");
  7. ofstream fout ("apm.out");
  8.  
  9. pair < int , int > P[nmax];
  10. int n, m, total, TT[nmax], k, RG[nmax];
  11.  
  12. struct Edge {
  13.     int x, y, c;
  14. }V[nmax];
  15.  
  16. bool fcmp (Edge a, Edge b) {
  17.     return a.c < b.c;
  18. }
  19.  
  20. void Read () {
  21.     fin >> n >> m;
  22.     for (int i = 1; i <= m; ++i) fin >> V[i].x >> V[i].y >> V[i].c;
  23.     sort (V + 1, V + m + 1, fcmp);
  24. }
  25.  
  26. int Find (int x) {
  27.     int R, y;
  28.     for (R = x; TT[R] != R; R = TT[R]);
  29.     for ( ; TT[x] != x;) {
  30.         y = TT[x];
  31.         TT[x] = R;
  32.         x = y;
  33.     }
  34.     return R;
  35. }
  36.  
  37. void Unite (int x, int y) {
  38.     if (RG[x] > RG[y]) TT[y] = x;
  39.     else TT[x] = y;
  40.     if (RG[x] == RG[y]) RG[y] ++;
  41. }
  42.  
  43. void Solve () {
  44.     for (int i = 1; i <= m; ++i) {
  45.         RG[i] = 1;
  46.         TT[i] = i;
  47.     }
  48.     for (int i = 1; i <= m; ++i) {
  49.         int xx = Find (V[i].x), yy = Find (V[i].y);
  50.         if (xx != yy) {
  51.             Unite (xx, yy);
  52.             P[++k] = {V[i].x, V[i].y};
  53.             total += V[i].c;
  54.         }
  55.     }
  56. }
  57.  
  58. void Print () {
  59.     fout << total << '\n' << n - 1 << '\n';
  60.     for (int i = 1; i <= k; ++i) fout << P[i].first << ' ' << P[i].second << ' ' << '\n';
  61. }
  62.  
  63. void Close () {
  64.     fin.close();
  65.     fout.close();
  66. }
  67.  
  68. int main() {
  69.     Read ();
  70.     Solve ();
  71.     Print ();
  72.     Close ();
  73.     return 0;
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment