Problem definition: Give the program that implement Prim’s algorithm. Input: Fir
ID: 3848727 • Letter: P
Question
Problem definition:
Give the program that implement Prim’s algorithm.
Input:
First line is N, denotes the amount of test case, then there are Ns graph data with an option number (determine whether output the selected edges or not).
Each graph is undirected and connected, it is composed of V (the number of vertices, <= 1000), E (the number of edges, <=10000), then followed by Es edges which are denoted by pair of vertex and weight (e.g., 2 4 10 means an edge connecting vertices 2 and 4, and its weight is 10).
The first data of each measurement on behalf of the test vertex number, edge number and option number.
The first data’s weight of each graph is option number. It could be 1 or 2, output the selected edge and the sum of all minimum spanning tree’s weight if it is 1, or only the sum if it is 2.
We restrict that selected node of Prim always start from 0, and there is no “tree edge” with same weight.
Output:
If option is 1:
The selected edges which forms the spanning tree. Order is important! The sum of all edges weight in minimum spanning tree. Note that the edge should put smaller node first, e.g., if the edge (4, 2) is selected, it should be output by 2 4, not 4 2.
If option is 2:
The sum of all edges weight in minimum spanning tree.
Example:
Input:
2
5 7 1
0 2 1
2 1 6
4 2 7
1 4 2
1 3 5
3 0 3
3 2 4
6 12 2
1 0 5
0 4 1
4 5 10
4 3 4
3 0 9
0 5 2
2 0 8
2 1 3
5 2 11
2 3 6
3 5 7
1 5 12
Output: (Prim’s algorithm)
0 2
0 3
1 3
1 4
11
15
please using c++ programming language and follow my INPUT and OUTPUT formats ,thank you .
Explanation / Answer
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10],u;
main()
{
int m,c;
cout <<"enterno of vertices";
cin >> n;
cout <<"ente no of edges";
cin >> m;
cout <<" EDGES Cost ";
for(k=1;k<=m;k++)
{
cin >>i>>j>>c;
cost[i][j]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
cout <<"ORDER OF VISITED VERTICES";
k=1;
while(k<n)
{
m=31999;
if(k==1)
{
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
if(cost[i][j]<m)
{
m=cost[i][j];
u=i;
}
}
else
{
for(j=n;j>=1;j--)
if(cost[v][j]<m && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
m=cost[v][j];
u=j;
}
}
cost[v][u]=31999;
v=u;
cout<<v << " ";
k++;
visit[v]=0; visited[v]=1;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.