Skip to content

Instantly share code, notes, and snippets.

@sauravgpt
Created May 30, 2021 09:43
Show Gist options
  • Save sauravgpt/013961078b4cd0ce802e8d12b7b7a5ba to your computer and use it in GitHub Desktop.
Save sauravgpt/013961078b4cd0ce802e8d12b7b7a5ba to your computer and use it in GitHub Desktop.
Implementing Prim's Brute Force Code
#include "./../my_lib.h"
vector<pair<int, int>> adj[100005];
void primsBrute(int V) {
vector<int> key(V, INT_MAX);
vector<int> parent(V, -1);
vector<bool> MST(V, false);
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int mini = INT_MAX, u;
for (int i = 0; i < V; i++) {
if (MST[i] == false && key[i] < mini)
mini = key[i], u = i;
}
MST[u] = true;
for (auto it : adj[u]) {
int v = it.first;
int w = it.second;
if (MST[v] == false && w < key[v]) {
key[v] = w;
parent[v] = u;
}
}
}
cout << "{ u, v, w } " << endl;
for (int i = 0; i < V; i++) {
cout << "{ " << i << ", " << parent[i] << ", " << key[i] << endl;
}
}
int main() {
int V, m;
cin >> V >> m;
int a, b, w;
for (int i = 1; i <= m; i++) {
cin >> a >> b >> w;
adj[a].push_back({ b, w });
adj[b].push_back({ a, w });
}
primsBrute(V);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment