Skip to content
Snippets Groups Projects
Commit 9e85ecc3 authored by Bruno Freitas Tissei's avatar Bruno Freitas Tissei
Browse files

Add prim algorithm

parent 26351f4a
No related branches found
No related tags found
No related merge requests found
/**
* Prim
*
* Complexity (Time): O(m log m)
* Complexity (Space): O(n + m)
*/
bool cont[MAX];
vector<ii> graph[MAX];
// Returns value of MST of graph
int prim() {
mset(cont, false);
cont[0] = true;
// Add negative values to pq in order to give priority
// to the edge with the smallest weight
priority_queue<ii> pq;
for (auto i : graph[0])
pq.push(ii(-i.se, -i.fi));
// At each step, connect vertex with smallest weight to the MST
int ans = 0;
while (!pq.empty()) {
ii front = pq.top(); pq.pop();
int u = -front.se;
int w = -front.fi;
if (!cont[u]) {
ans += w;
cont[u] = true;
for (auto i : graph[u])
if (!cont[i.fi])
pq.push(ii(-i.se, -i.fi));
}
}
return ans;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment