TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
prim.cpp
1// C++ program to implement Prim's Algorithm
2#include <iostream>
3#include <queue>
4#include <vector>
5
6using PII = std::pair<int, int>;
7
8int prim(int x, const std::vector<std::vector<PII> > &graph) {
9 // priority queue to maintain edges with respect to weights
10 std::priority_queue<PII, std::vector<PII>, std::greater<PII> > Q;
11 std::vector<bool> marked(graph.size(), false);
12 int minimum_cost = 0;
13
14 Q.push(std::make_pair(0, x));
15 while (!Q.empty()) {
16 // Select the edge with minimum weight
17 PII p = Q.top();
18 Q.pop();
19 x = p.second;
20 // Checking for cycle
21 if (marked[x] == true) {
22 continue;
23 }
24 minimum_cost += p.first;
25 marked[x] = true;
26 for (const PII &neighbor : graph[x]) {
27 int y = neighbor.second;
28 if (marked[y] == false) {
29 Q.push(neighbor);
30 }
31 }
32 }
33 return minimum_cost;
34}
35
36int main() {
37 int nodes = 0, edges = 0;
38 std::cin >> nodes >> edges; // number of nodes & edges in graph
39 if (nodes == 0 || edges == 0) {
40 return 0;
41 }
42
43 std::vector<std::vector<PII> > graph(nodes);
44
45 // Edges with their nodes & weight
46 for (int i = 0; i < edges; ++i) {
47 int x = 0, y = 0, weight = 0;
48 std::cin >> x >> y >> weight;
49 graph[x].push_back(std::make_pair(weight, y));
50 graph[y].push_back(std::make_pair(weight, x));
51 }
52
53 // Selecting 1 as the starting node
54 int minimum_cost = prim(1, graph);
55 std::cout << minimum_cost << std::endl;
56 return 0;
57}
int main()
Main function.
Graph Algorithms.