fork download
  1. #include<iostream>
  2. using namespace std;
  3. int a,b,u,v,n,i,j,ne=1;
  4. int visited[10]={0},mini,mincost=0,cost[10][10];
  5. int main()
  6. {
  7.  
  8. cout<<"\n Enter the number of nodes:";
  9. cin>>n;
  10. cout<<"\n Enter the adjacency matrix:\n";
  11. for(i=1;i<=n;i++)
  12. for(j=1;j<=n;j++)
  13. {
  14. cin>>cost[i][j];
  15. if(cost[i][j]==0)
  16. cost[i][j]=999;
  17. }
  18. visited[1]=1;
  19. cout<<endl;
  20. while(ne<n)
  21. {
  22. for(i=1,mini=999;i<=n;i++)
  23. for(j=1;j<=n;j++)
  24. if(cost[i][j]<mini)
  25. if(visited[i]!=0)
  26. {
  27. mini=cost[i][j];
  28. a=u=i;
  29. b=v=j;
  30. }
  31. if(visited[u]==0 || visited[v]==0)
  32. {
  33. cout<<"\n Edge "<<ne++<<":( "<<a<<" "<<b<<") cost:"<<mini;
  34. mincost+=mini;
  35. visited[b]=1;
  36. }
  37. cost[a][b]=cost[b][a]=999;
  38. }
  39. cout<<"\n Minimun cost= "<<mincost;
  40. cout<<endl;
  41. return 0;
  42. }
Success #stdin #stdout 0s 15232KB
stdin
6
0 3 0 0 6 5
3 0 1 0 0 4
0 1 0 6 0 4 
0 0 6 0 8 5
6 0 0 8 0 2
5 4 4 5 2 8
0
stdout
 Enter the number of nodes:
 Enter the adjacency matrix:


 Edge 1:( 1 2) cost:3
 Edge 2:( 2 3) cost:1
 Edge 3:( 2 6) cost:4
 Edge 4:( 6 5) cost:2
 Edge 5:( 6 4) cost:5
 Minimun cost= 15