

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Prim's Algorithm is greedy algorithm. It works on bases of minimum spanning tree. Prim Algorithm is also known as DJP algorithm, the Jarník algorithm, the Prim–Jarník algorithm. In this file, Prim algorithm is implemented using C++ language. Its working code.
Typology: Study Guides, Projects, Research
1 / 2
This page cannot be seen from the preview
Don't miss anything!


#include<iostream.h> #include
using namespace std;
struct edge { vector
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
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; }