# Prim Algorithm - C plus plus Code, Projects for Computer Programming

PDF (48 KB)
2 pages
1000+Number of visits
Description
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 implement...
40 points
this document
Preview2 pages / 2
Microsoft Word - Prim Algorithm

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