fork download
  1. #include<stdio.h>
  2. int cost[10][10],n;
  3. void kruskal()
  4. {
  5. int par[n];
  6. int a=0,b=0,u=0,v=0,min, mincost = 0, ne = 0;
  7. for(int i=0;i<n;i++)
  8. par[i]=-1;
  9. printf("the minimum spanning tree edges are...");
  10. while(ne < n-1)
  11. {
  12. //Find the least cost edge
  13. min = 999;
  14. for(int i=0;i<n;i++)
  15. for(int j=0;j<n;j++)
  16. if(cost[i][j] < min)
  17. {
  18. min=cost[i][j];
  19. a=u=i;
  20. b=v=j;
  21. }
  22. //Check if edge select cause cyclicity?
  23. while(par[u]!=-1)
  24. u=par[u];
  25. while(par[v]!=-1)
  26. v=par[v];
  27. if(u!=v)
  28. {
  29. printf("From vertex %d to vertex %d and the cost = %d\n",a,b,min);
  30. mincost+=min;
  31. par[v]=u;
  32. ne++;
  33. }
  34. //edge included in MST should not be considered for next iteration
  35. cost[a][b]=cost[b][a]=999;
  36. }
  37. printf("Cost of MST = %d", mincost);
  38. }
  39.  
  40. void main()
  41. {
  42. printf("Enter the no. of vertices:");
  43. scanf("%d",&n);
  44. printf("Enter the cost matrix\n");
  45. for(int i=0;i<n;i++)
  46. for(int j=0;j<n;j++)
  47. scanf("%d",&cost[i][j]);
  48. kruskal();
  49. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Enter the no. of vertices:Enter the cost matrix
the minimum spanning tree edges are...Cost of MST = 0