Advertisement
monyca98

prim

May 25th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<vector>
  4. #include<queue>
  5. #include<algorithm>
  6. #include<functional>
  7. using namespace std;
  8. typedef pair<int, int> p;
  9.  
  10. #define INF 999
  11. #define max_size 10000
  12.  
  13. priority_queue<p, vector<p>, greater<p>> q;
  14. vector<int> g[max_size];
  15. vector<p> need;  //first wil be the parent,second the rank
  16. int n, m;
  17. vector<int> inMST; // if a vertice is already in MST or no
  18.  
  19. void read()
  20. {
  21.     ifstream in("file.txt");
  22.     if (in.is_open())
  23.     {
  24.         in >> n >> m;
  25.         int x, y, w;
  26.         for (int i = 0; i<=n; i++)
  27.         {
  28.             g[i].assign(n+1, 0);
  29.         }
  30.         inMST.assign(n + 1, 0);
  31.  
  32.         for (int i = 0; i<m; i++)
  33.         {
  34.             in >> x >> y >> w;
  35.             g[x][y] = w;
  36.             g[y][x] = w;
  37.         }
  38.     }
  39.     else
  40.         cout << "Unable to open the file\n";
  41.  
  42. }
  43.  
  44. void prim()
  45. {
  46.     int source = 1;
  47.     need.assign(n+1, { -1,INF });
  48.     q.push({ 0,source });
  49.     need[source].second = 0;
  50.  
  51.     while (!q.empty())
  52.     {
  53.         p e = q.top();
  54.         int u=e.second;
  55.         q.pop();
  56.         inMST[u] = 1;
  57.         for (int j = 1; j <= n; j++)
  58.             {
  59.                 int v = j;
  60.                 int w = g[u][j];
  61.                 if (w!=0 && inMST[v] == 0 && need[v].second>w)
  62.                 {
  63.                     need[v].second = w;
  64.                     q.push({ need[v].second,v });
  65.                     need[v].first = u;
  66.                 }
  67.  
  68.             }
  69.     }
  70.  
  71.  
  72. }
  73. int main()
  74. {
  75.     read();
  76.     prim();
  77.     cout << "MST:\n";
  78.     for (int i = 1; i<=n; i++)
  79.         if(need[i].first!=-1)
  80.             cout << need[i].first << " " << i<<endl;
  81.     return 0;
  82. }
  83.  
  84. /*
  85. 7 11
  86. 1 2 7
  87. 1 7 5
  88. 2 3 8
  89. 2 4 7
  90. 2 7 9
  91. 3 4 5
  92. 4 5 9
  93. 4 6 8
  94. 4 7 15
  95. 5 6 11
  96. 6 7 6
  97.  
  98. should print : 1 7,3 4,6 7,1 2,4 5,4 2
  99. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement