Advertisement
shabbyheart

Prims Algorithm using matrix

Jan 4th, 2020
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int adj[1000][1000];
  5. class Node{
  6. public:
  7.     int v,cost;
  8.     Node()
  9.     {
  10.  
  11.     }
  12.     Node(int vertex,int costt)
  13.     {
  14.         v= vertex;
  15.         cost = costt;
  16.     }
  17.  
  18. };
  19. bool operator<(Node a,Node b)
  20. {
  21.     return a.cost>b.cost;
  22. }
  23. class Prims{
  24.         int vertex,edge,u,v,weight,i,j,ans = 0;
  25.         bool visited[100] = {false};
  26. public:
  27.     void input()
  28.     {
  29.         cin>>vertex>>edge;
  30.         for(int i=1; i<=edge;i++)
  31.         {
  32.             cin>>u>>v>>weight;
  33.             adj[u][v] = weight;
  34.             adj[v][u] = weight;
  35.         }
  36.     }
  37.     void solution()
  38.     {
  39.         priority_queue<Node>pq;
  40.         pq.push(Node(0,0));
  41.         int parent[100]={0};
  42.         while(!pq.empty())
  43.         {
  44.             Node temp = pq.top();
  45.             pq.pop();
  46.             if(visited[temp.v] == 1) continue;
  47.             cout<<parent[temp.v]<<" "<<temp.v<<" "<<temp.cost<<endl;
  48.             //parent = temp.v;
  49.             ans +=temp.cost;
  50.             visited[temp.v] =1;
  51.             for(i = 0;i<vertex;i++)
  52.             {
  53.                 /// for loop not create
  54.                 if(visited[i] == 1)
  55.                 {
  56.                     continue;
  57.                 }
  58.                 /// skip some vertex that are not adjacent
  59.                 if(adj[temp.v][i] !=0)
  60.                 {
  61.                     pq.push(Node(i,adj[temp.v][i]));
  62.                     parent[i]= temp.v;
  63.                     //cout<<i<<" "<<adj[temp.v][i]<<endl;
  64.                 }
  65.             }
  66.         }
  67.         cout<<endl<<"Minimum cost is "<<ans<<endl;
  68.     }
  69. };
  70. int main()
  71. {
  72.     freopen("input.txt","r",stdin);
  73.  
  74.     Prims p;
  75.     p.input();
  76.     p.solution();
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement