-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrimsAlgorithm.cpp
88 lines (76 loc) · 2 KB
/
PrimsAlgorithm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter The Number of vertex: ";
cin >> n;
int edge;
cout << "Enter The Number of Edges: ";
cin>> edge;
int st,l=1;
cout << "Enter The Starting Node: " ;
cin >> st;
if(st>0)
{
n+=1;
l = 2;
}
vector<pair<int, int > > adj[n];
/*Take Input for Graph */
for(int i =0; i<edge; i++)
{
int u,v,wt;
cin >> u >> v >> wt;
adj[u].push_back({v, wt});
adj[v].push_back({u, wt});
}
priority_queue< pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
int key[n]; // weight stored for the visited node
int parent[n]; // when the weight changed then the parent will be added there
bool inMST[n]; // node visited or not
for(int i=0; i<n; i++)
{
key[i]=INT_MAX; // Every key value made infinity.
inMST[i]= false;// Visiting node all false.
}
key[st] = 0;
parent[st]=-1;
pq.push({0,st}); // this pair: first value weight for this node, second value node
while(!pq.empty())
{
int p_node = pq.top().second;//staring node
pq.pop();
inMST[p_node] = true;
for(auto it:adj[p_node])
{
int v = it.first; // under staring node all nodes
int weight = it.second; // current node weight
if(inMST[v]==false && weight<key[v])
{
key[v] = weight; // under staring node all node
parent[v] = p_node; // changed weight parent valuse added.
pq.push({key[v], v});
}
}
}
int cost =0;
cout << "Primes MST: " << endl;
for(int i =l; i<n; i++)
{
cost+=key[i];
cout << parent[i] << " - " << i << endl;
}
cout << "Total Cost: " << cost << endl;
return 0;
}
/*
Input Value:
4 6
1 2 2
1 3 1
1 4 3
2 3 4
2 4 1
3 4 2
*/