Docsity

Prim Algorithm - C plus plus Code, Study Guides, Projects, Research of Computer Programming

Toggle sidebar
bg1
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
pf2

Partial preview of the text

Download Prim Algorithm - C plus plus Code and more Study Guides, Projects, Research Computer Programming in PDF only on Docsity!

Prim’s Algorithm- MST

#include<iostream.h> #include #include #define INF 100000

using namespace std;

struct edge { vectorAdj; vectorCost; };

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, 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