Advertisement
pexea12

Prim

Apr 26th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4.  
  5. using namespace std;
  6.  
  7. const int MAX_WEIGHT = 1000000;
  8.  
  9. int n, m;
  10. int **w;
  11.  
  12. void init() {
  13.     cin >> n >> m;
  14.    
  15.     w = new int*[n];
  16.     for (int i = 0; i < n; ++i) w[i] = new int[n];
  17.    
  18.     for (int i = 0; i < m; ++i) {
  19.         int start, end, weight;
  20.         cin >> start >> end >> weight;
  21.         w[start][end] = w[end][start] = weight;
  22.     }
  23. }
  24.  
  25. int prim() {
  26.     bool *check = new bool[n];
  27.     vector<int> select;
  28.     check[0] = true;
  29.    
  30.     int total = 0;
  31.    
  32.     select.push_back(0);
  33.    
  34.     while (select.size() < n) {
  35.         int minWeight = MAX_WEIGHT;
  36.         int next = -1;
  37.        
  38.         for (int i = 0; i < select.size(); ++i)
  39.             for (int j = 0; j < n; ++j)
  40.                 if (w[select[i]][j] > 0 && !check[j])
  41.                     if (w[select[i]][j] < minWeight) {
  42.                         minWeight = w[select[i]][j];
  43.                         next = j;
  44.                     }
  45.        
  46.         if (next == -1) {
  47.             cerr << "No minimum spanning tree";
  48.             exit(1);
  49.         }
  50.        
  51.         check[next] = true;
  52.         total += minWeight;
  53.         select.push_back(next);
  54.     }
  55.    
  56.     return total;
  57. }
  58.  
  59. int main()
  60. {
  61.     init();
  62.     cout << "Minimum spanning tree weight: " << prim() << endl;
  63.    
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement