Skip to content

Commit c4a8a95

Browse files
authored
Merge pull request larissalages#53 from imakshat01/master
Created prims_algo.cpp
2 parents 039de9a + 6286e25 commit c4a8a95

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <queue>
4+
#include <functional>
5+
#include <utility>
6+
7+
using namespace std;
8+
const int MAX = 1e4 + 5;
9+
typedef pair<long long, int> PII;
10+
bool marked[MAX];
11+
vector <PII> adj[MAX];
12+
13+
long long prim(int x)
14+
{
15+
priority_queue<PII, vector<PII>, greater<PII> > Q;
16+
int y;
17+
long long minimumCost = 0;
18+
PII p;
19+
Q.push(make_pair(0, x));
20+
while(!Q.empty())
21+
{
22+
// Select the edge with minimum weight
23+
p = Q.top();
24+
Q.pop();
25+
x = p.second;
26+
// Checking for cycle
27+
if(marked[x] == true)
28+
continue;
29+
minimumCost += p.first;
30+
marked[x] = true;
31+
for(int i = 0;i < adj[x].size();++i)
32+
{
33+
y = adj[x][i].second;
34+
if(marked[y] == false)
35+
Q.push(adj[x][i]);
36+
}
37+
}
38+
return minimumCost;
39+
}
40+
41+
int main()
42+
{
43+
int nodes, edges, x, y;
44+
long long weight, minimumCost;
45+
cin >> nodes >> edges;
46+
for(int i = 0;i < edges;++i)
47+
{
48+
cin >> x >> y >> weight;
49+
adj[x].push_back(make_pair(weight, y));
50+
adj[y].push_back(make_pair(weight, x));
51+
}
52+
// Selecting 1 as the starting node
53+
minimumCost = prim(1);
54+
cout << minimumCost << endl;
55+
return 0;
56+
}

0 commit comments

Comments
 (0)