Alex_tz307

Prim APM

Sep 11th, 2020 (edited)
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin ("apm.in");
  6. ofstream fout ("apm.out");
  7.  
  8. typedef pair < int, int > Pair;
  9. int N, M, ans;
  10. vector < Pair > G[200002];
  11. list < Pair > sol;
  12.  
  13. void Read () {
  14.   fin >> N >> M;
  15.   while (M --) {
  16.     int u, v, wt;
  17.     fin >> u >> v >> wt;
  18.     G[u].push_back ({v, wt});
  19.     G[v].push_back ({u, wt});
  20.   }
  21. }
  22.  
  23. void Prim ()  {
  24.   priority_queue < Pair, vector < Pair > , greater < Pair > > Heap;
  25.   vector < int > key (N + 2, INT_MAX),
  26.                  parent (N + 2);
  27.   vector < bool > viz (N + 2, 0);
  28.   Heap.push ({0, 1});
  29.   key[1] = 0;
  30.   while (!Heap.empty())  {
  31.     int u = Heap.top().second;
  32.     Heap.pop();
  33.     viz[u] = true;
  34.     for (auto it : G[u])  {
  35.       int v = it.first, weight = it.second;
  36.       if (viz[v] == false && key[v] > weight)  {
  37.         key[v] = weight;
  38.         Heap.push ({key[v], v});
  39.         parent[v] = u;
  40.       }
  41.     }
  42.   }
  43.   for (int i = 2; i <= N; i ++) {
  44.     sol.push_back ({parent[i], i});
  45.     ans += key[i];
  46.   }
  47. }
  48.  
  49. void Solve () {
  50.   Read();
  51.   Prim();
  52.   fout << ans << '\n' << N - 1 << '\n';
  53.   for (auto it : sol)
  54.     fout << it.first << ' ' << it.second << '\n';
  55. }
  56.  
  57. int main() {
  58.   Solve();
  59.   return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment