Skip to content

Commit

Permalink
Update and rename C++ to primsalgo.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Achlesha authored Oct 5, 2022
1 parent 5011f11 commit 4407a3d
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
1 change: 0 additions & 1 deletion C++

This file was deleted.

54 changes: 54 additions & 0 deletions primsalgo.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}

0 comments on commit 4407a3d

Please sign in to comment.