Advertisement
sp_Showrav

Prims Code

Aug 3rd, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include<iostream>
  2. #include<queue>
  3. #include<string.h>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. int n,e,edge[100][100];
  9.  
  10. struct node
  11. {
  12.     int cost, vertex;
  13. };
  14.  
  15. bool operator<(node a, node b)
  16. {
  17.     return a.cost>b.cost;
  18. }
  19. int prims()
  20. {
  21.     bool visited[100];
  22.  
  23.     memset(visited, false, sizeof(visited));
  24.     node temp;
  25.  
  26.     temp.cost=0;
  27.     temp.vertex=0;
  28.  
  29.     priority_queue<node>pq;
  30.     pq.push(temp);
  31.  
  32.     int ans=0;
  33.  
  34.     while(!pq.empty())
  35.     {
  36.         node cur = pq.top();
  37.         pq.pop();
  38.  
  39.         if(visited[cur.vertex])
  40.         {
  41.             continue;
  42.         }
  43.         visited[cur.vertex] = true;
  44.         ans=ans+cur.cost;
  45.  
  46.  
  47.         for(int i=0; i<n; i++)
  48.         {
  49.             if(edge[cur.vertex][i] >=0)
  50.             {
  51.                 node t;
  52.                 t.cost=edge[cur.vertex][i];
  53.                 t.vertex=i;
  54.  
  55.  
  56.                 if(visited[i] == false)
  57.                 {
  58.                     pq.push(t);
  59.                 }
  60.             }
  61.         }
  62.     }
  63.     return ans;
  64. }
  65.  
  66. int main()
  67. {
  68.     while(cin>>n>>e)
  69.     {
  70.         for(int i=0; i<n; i++)
  71.         {
  72.             for(int j=0; j<n; j++)
  73.             {
  74.                 edge[i][j]=-1;;
  75.             }
  76.         }
  77.         for(int i=0; i<e; i++)
  78.         {
  79.             int a,b,c;
  80.             cin>>a>>b>>c;
  81.  
  82.             edge[a][b]=c;
  83.             edge[b][a]=c;
  84.         }
  85.         int ans = prims();
  86.         cout<<ans<<endl;
  87.     }
  88.  
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement