From 9e85ecc322be50ceaaeb6d505b7dd79677790acd Mon Sep 17 00:00:00 2001 From: Bruno Freitas Tissei <bft15@inf.ufpr.br> Date: Mon, 18 Feb 2019 10:56:43 -0300 Subject: [PATCH] Add prim algorithm Signed-off-by: Bruno Freitas Tissei <bft15@inf.ufpr.br> --- algorithms/graph/prim.cpp | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 algorithms/graph/prim.cpp diff --git a/algorithms/graph/prim.cpp b/algorithms/graph/prim.cpp new file mode 100644 index 0000000..1229061 --- /dev/null +++ b/algorithms/graph/prim.cpp @@ -0,0 +1,40 @@ +/** + * 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; +} -- GitLab