Advertisement
warrior98

prim

May 20th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MOD 1000000007
  3. #define NMAX 200005
  4. #define INF 0x3f3f3f3f
  5. #define pb push_back
  6.  
  7. using namespace std;
  8.  
  9. long long fact[NMAX];
  10.  
  11. ifstream fin("fisier.in");
  12. ofstream fout("fisier.out");
  13.  
  14. vector<pair<int,int> > G[NMAX];
  15. vector<pair<int,int> > sol;
  16. bool inSolution[NMAX];
  17.  
  18. int main() {
  19.     int n,m,i,x,y,c,cost=0;
  20.  
  21.     fin>>n>>m;
  22.  
  23.     for(i=1;i<=m;++i) {
  24.         fin>>x>>y>>c;
  25.  
  26.         G[x].pb({c,y});
  27.         G[y].pb({c,x});
  28.     }
  29.  
  30.     priority_queue<pair<pair<int,int>, int>, vector<pair<pair<int,int>, int> >, greater<pair<pair<int,int>, int > > > pq;
  31.     inSolution[1] = 1;
  32.     for(i=0;i<G[1].size();++i) pq.push({G[1][i], 1});
  33.  
  34.     while((int)sol.size() < n-1) {
  35.         pair<pair<int,int>, int> muchie = pq.top();
  36.         pq.pop();
  37.  
  38.         int x = muchie.second, y = muchie.first.second;
  39.         if(!inSolution[y]) {
  40.             inSolution[y] = 1;
  41.             cost+=muchie.first.first;
  42.  
  43.             for(i=0;i<G[y].size();++i) pq.push({G[y][i], y});
  44.  
  45.             sol.push_back({x, y});
  46.         }
  47.     }
  48.  
  49.     fout << cost << '\n' << sol.size() << '\n';
  50.     for(auto it:sol)
  51.         fout << it.first << ' ' << it.second << '\n';
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement