al__nasim

prims.cpp

Jan 9th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int G[100][100],spanning[100][100],n;
  6.  
  7. int prims()
  8. {
  9.     int cost[100][100];
  10.     int u,v,min_distance,distance[100],from[100];
  11.     int visited[100],no_of_edges,i,min_cost,j;
  12.  
  13.     //create cost[][] matrix,spanning[][]
  14.     for(i=0;i<n;i++){
  15.         for(j=0;j<n;j++)
  16.         {
  17.             if(G[i][j]==0) cost[i][j]=999;
  18.             else
  19.             {
  20.                 cost[i][j]=G[i][j];
  21.                 spanning[i][j]=0;
  22.             }
  23.         }
  24.     }
  25.     //initialize visited[],distance[] and from[]
  26.     distance[0]=0;
  27.     visited[0]=1;
  28.  
  29.     for(i=1;i<n;i++)
  30.     {
  31.         distance[i]=cost[0][i];
  32.         from[i]=0;
  33.         visited[i]=0;
  34.     }
  35.  
  36.     min_cost=0;        //cost of spanning tree
  37.     no_of_edges=n-1;        //no. of edges to be added
  38.  
  39.     while(no_of_edges>0)
  40.     {
  41.         //find the vertex at minimum distance from the tree
  42.         min_distance=999;
  43.         for(i=1;i<n;i++){
  44.             if(visited[i]==0&&distance[i]<min_distance)
  45.             {
  46.                 v=i;
  47.                 min_distance=distance[i];
  48.             }
  49.         }
  50.         u=from[v];
  51.  
  52.         //insert the edge in spanning tree
  53.         spanning[u][v]=distance[v];
  54.         spanning[v][u]=distance[v];
  55.         no_of_edges--;
  56.         visited[v]=1;
  57.  
  58.         //updated the distance[] array
  59.         for(i=1;i<n;i++){
  60.             if(visited[i]==0&&cost[i][v]<distance[i])
  61.             {
  62.                 distance[i]=cost[i][v];
  63.                 from[i]=v;
  64.             }
  65.         }
  66.         min_cost=min_cost+cost[u][v];
  67.     }
  68.     return(min_cost);
  69. }
  70.  
  71. int main()
  72. {
  73.     int i,j,total_cost;
  74.     cout <<"Enter the vertices :";
  75.     cin >>n;
  76.     cout <<"The matrix : " <<endl;
  77.     for(i=0;i<n;i++) for(j=0;j<n;j++) cin >> G[i][j];
  78.  
  79.     total_cost=prims();
  80.     cout <<"Spanning tree matrix :" <<endl;
  81.  
  82.     for(i=0;i<n;i++)
  83.     {
  84.         for(j=0;j<n;j++)
  85.              if(spanning[i][j]!=0)
  86.              {
  87.                 cout <<"from "<<i<<"to "<<j<< " "<<spanning[i][j];
  88.                 spanning[j][i]=0;
  89.              }
  90.  
  91.             cout <<endl;
  92.     }
  93.     cout << "MST is : "<<total_cost<<endl;
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment