forked from Achlesha/hactoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
primsalgo.cpp
54 lines (38 loc) · 1.08 KB
/
primsalgo.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
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,m;
cin >> N >> m;
vector<pair<int,int> > adj[N];
int a,b,wt;
for(int i = 0; i<m ; i++){
cin >> a >> b >> wt;
adj[a].push_back(make_pair(b,wt));
adj[b].push_back(make_pair(a,wt));
}
int parent[N];
int key[N];
bool mstSet[N];
for (int i = 0; i < N; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
int ansWeight = 0;
for (int count = 0; count < N - 1; count++)
{
int mini = INT_MAX, u;
for (int v = 0; v < N; v++)
if (mstSet[v] == false && key[v] < mini)
mini = key[v], u = v;
mstSet[u] = true;
for (auto it : adj[u]) {
int v = it.first;
int weight = it.second;
if (mstSet[v] == false && weight < key[v])
parent[v] = u, key[v] = weight;
}
}
for (int i = 1; i < N; i++)
cout << parent[i] << " - " << i <<" \n";
return 0;
}