2020-05-21 23:25:53 +08:00
|
|
|
// C++ program to implement Prim's Algorithm
|
|
|
|
#include <iostream>
|
|
|
|
#include <queue>
|
2020-06-20 00:04:56 +08:00
|
|
|
#include <vector>
|
2020-05-21 23:25:53 +08:00
|
|
|
|
2020-08-09 00:29:02 +08:00
|
|
|
using PII = std::pair<int, int>;
|
2020-05-21 23:25:53 +08:00
|
|
|
|
2020-08-27 22:28:31 +08:00
|
|
|
int prim(int x, const std::vector<std::vector<PII> > &graph) {
|
2020-05-21 23:25:53 +08:00
|
|
|
// priority queue to maintain edges with respect to weights
|
2020-06-20 00:04:56 +08:00
|
|
|
std::priority_queue<PII, std::vector<PII>, std::greater<PII> > Q;
|
2020-08-08 08:52:38 +08:00
|
|
|
std::vector<bool> marked(graph.size(), false);
|
|
|
|
int minimum_cost = 0;
|
2020-05-21 23:25:53 +08:00
|
|
|
|
2020-06-20 00:04:56 +08:00
|
|
|
Q.push(std::make_pair(0, x));
|
2020-05-21 23:25:53 +08:00
|
|
|
while (!Q.empty()) {
|
|
|
|
// Select the edge with minimum weight
|
2020-08-08 08:52:38 +08:00
|
|
|
PII p = Q.top();
|
2020-05-21 23:25:53 +08:00
|
|
|
Q.pop();
|
|
|
|
x = p.second;
|
|
|
|
// Checking for cycle
|
2020-08-08 08:52:38 +08:00
|
|
|
if (marked[x] == true) {
|
2020-05-21 23:25:53 +08:00
|
|
|
continue;
|
2020-08-08 08:52:38 +08:00
|
|
|
}
|
|
|
|
minimum_cost += p.first;
|
2020-05-21 23:25:53 +08:00
|
|
|
marked[x] = true;
|
2020-08-08 08:52:38 +08:00
|
|
|
for (const PII &neighbor : graph[x]) {
|
|
|
|
int y = neighbor.second;
|
|
|
|
if (marked[y] == false) {
|
|
|
|
Q.push(neighbor);
|
|
|
|
}
|
2020-05-21 23:25:53 +08:00
|
|
|
}
|
|
|
|
}
|
2020-08-08 08:52:38 +08:00
|
|
|
return minimum_cost;
|
2020-05-21 23:25:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
2020-08-08 08:52:38 +08:00
|
|
|
int nodes = 0, edges = 0;
|
2020-06-20 00:04:56 +08:00
|
|
|
std::cin >> nodes >> edges; // number of nodes & edges in graph
|
2020-08-08 08:52:38 +08:00
|
|
|
if (nodes == 0 || edges == 0) {
|
2020-05-21 23:25:53 +08:00
|
|
|
return 0;
|
2020-08-08 08:52:38 +08:00
|
|
|
}
|
|
|
|
|
2020-08-27 22:28:31 +08:00
|
|
|
std::vector<std::vector<PII> > graph(nodes);
|
2020-05-21 23:25:53 +08:00
|
|
|
|
|
|
|
// Edges with their nodes & weight
|
|
|
|
for (int i = 0; i < edges; ++i) {
|
2020-08-08 08:52:38 +08:00
|
|
|
int x = 0, y = 0, weight = 0;
|
2020-05-21 23:25:53 +08:00
|
|
|
std::cin >> x >> y >> weight;
|
2020-08-08 08:52:38 +08:00
|
|
|
graph[x].push_back(std::make_pair(weight, y));
|
|
|
|
graph[y].push_back(std::make_pair(weight, x));
|
2020-05-21 23:25:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Selecting 1 as the starting node
|
2020-08-08 08:52:38 +08:00
|
|
|
int minimum_cost = prim(1, graph);
|
|
|
|
std::cout << minimum_cost << std::endl;
|
2020-05-21 23:25:53 +08:00
|
|
|
return 0;
|
|
|
|
}
|