-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimsAlgoFindingWeightEdgesGFG.cpp
52 lines (43 loc) · 1.27 KB
/
primsAlgoFindingWeightEdgesGFG.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
// THE GFG practice section problem has faulty test case, it says the nodes are 0-based, but it has 0-based nodes and also has nodes which are names as N.
// Hence be careful while submitting the code at GFG
// THe below code runs fine.
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
//Function to find sum of weights of edges of the Minimum Spanning Tree.
int spanningTree(int N, vector<vector<int>> adj[])
{
int parent[N+1];
int key[N+1];
bool mstSet[N+1];
for(int i=0;i<=N;i++)
key[i]=INT_MAX, mstSet[i]=false;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>>pq;
key[0]=0;
parent[0]=-1;
pq.push({0,0});
while(!pq.empty());
{
int u=pq.top().second;
pq.pop();
mstSet[u]=true;
for(auto it:adj[u]){
int v=it[0];
int weight=it[1];
if(mstSet[v]==false && weight<key[v])
{
parent[v]=u;
key[v]=weight;
pq.push({key[v],v});
}
}
}
int sum=0;
for(int i=1;i<=N;i++){
if(key[i]!=INT_MAX)
sum+=key[i];
}
retrun sum;
}
};