##### Document information

**Prim’s Algorithm- MST
**#include<iostream.h>
#include<queue>
#include<vector>
#define INF 100000
using namespace std;
struct edge {
vector<int>Adj;
vector<int>Cost;
};
struct node{
int x, y;
};
edge Ed[100];
int N, E;
int key[100];
char F[100];
int P[100], Cost;
int SS[100][100];
class comp{
public:
bool operator() ( const node &a, const node &b)
{
return a.y > b.y;
}
};
void CT(int u) {
if(F[u] == 1 || u == 1) return;
F[u] = 1;
if(P[u] == -1) return;
Cost += SS[u][P[u]];
CT(P[u]);
}
int Prim() {
int i, j, u, v, c,cost;
Cost = 0;
priority_queue<node, vector<node>, comp> Q;
node temp, dum;
for(i = 1; i<= N; i++)
key[i] = INF;
key[1] = 0;
temp.x = 1;
temp.y = 0;
Q.push(temp);
P[1] = -1;
while(!Q.empty()) {
temp = Q.top();
Q.pop();

docsity.com

u = temp.x; F[u] = 1; for(i = 0; i<Ed[u].Adj.size(); i++) { v = Ed[u].Adj[i]; c = Ed[u].Cost[i] + temp.y; if(F[v] == 0) { if(key[v] > c) { dum.x = v; dum.y = c; key[v] = c; P[v] = u; Q.push(dum); } } } } for(i = 1; i<= N; i++) F[i] = 0; for(i = 1; i<= N; i++) { if(F[i] == 0) CT(i); } return Cost; } void main() { int c, u, v, n; cin>>N>>E; n = E; while(n--) { cin>>u>>v>>c; Ed[u].Adj.push_back(v); Ed[u].Cost.push_back(c); Ed[v].Adj.push_back(u); Ed[v].Cost.push_back(c); SS[u][v] = SS[v][u] = c; } cout<<Prim()<<endl; }

docsity.com

Given a weighted graph G, a minimal cost spanning tree (MCST) T is a tree of G with the

smallest weight. We have discussed two algorithms for solving the MCST problem - Kruskal’s

algorithm and Prim’s algorithm. Both the algorithms use greedy approaches to solve the

problem. Now, do the following steps.

(i) Write programs in C++/java to implementing Kruskal’s and Prim’s algorithms.

(ii) Test your programs on (same for both algorithms) randomly generated test graphs of 50,

100, 150, 200, 250 and 300 vertices.

((Can I resolved in this code))