Advertisement
Guest User

Untitled

a guest
Oct 27th, 2017
558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. /*
  2.  ID: bradyawn
  3.  PROG: cf
  4.  LANG: C++11
  5.  */
  6.  
  7. #include <iostream>
  8. #include <algorithm>
  9. #include <iomanip>
  10. #include <fstream>
  11. #include <vector>
  12. #include <string>
  13. #include <cmath>
  14. #include <map>
  15. #include <utility>
  16. #include <algorithm>
  17. #include <set>
  18. #include <ctime>
  19. #include <queue>
  20. #include <stack>
  21.  
  22. #define ll long long
  23.  
  24.  
  25. //#define inf cin
  26. //#define outf cout
  27.  
  28. using namespace std;
  29.  
  30. int main()
  31. {
  32.     //ifstream inf("");
  33.     //fstream outf("");
  34.     //cout << setprecision(10);
  35.  
  36.     ll n, m;
  37.     cin >> n >> m;
  38.    
  39.     vector<vector<ll>> graph(n, vector<ll>());
  40.  
  41.     vector<vector<ll>> prim(n, vector<ll>(n));
  42.    
  43.     for (int i = 0; i < m; i++)
  44.     {
  45.         int a, b, c;
  46.         cin >> a >> b >> c;
  47.        
  48.         a--; b--;
  49.        
  50.         graph[a].push_back(b);
  51.         graph[b].push_back(a);
  52.        
  53.         prim[a][b] = c;
  54.         prim[b][a] = c;
  55.        
  56.        
  57.     }
  58.    
  59.     vector<ll> nodes;
  60.     vector<bool> vis(n);
  61.     nodes.push_back(0);
  62.     vis[0] = true;
  63.     ll ret = 0;
  64.    
  65.     while (nodes.size() < n) //when amnt nodes reaches total nodes, mst found
  66.     {
  67.         ll toVis = -1;
  68.         ll len = 1000001;
  69.         for (auto e : nodes) //loop possible start nodes
  70.         {
  71.             for (auto u : graph[e]) //vis nodes adj to start
  72.             {
  73.                 if (!vis[u]) //if not vis
  74.                 {
  75.                     if (prim[e][u] < len)
  76.                     {
  77.                         len = prim[e][u];
  78.                         toVis = u;
  79.                     }
  80.                 }
  81.             }
  82.         }
  83.        
  84.         ret += len;
  85.         vis[toVis] = true;
  86.         nodes.push_back(toVis);
  87.        
  88.     }
  89.    
  90.     cout << ret << endl;
  91.    
  92.     return 0;
  93.    
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement