Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <queue>
- struct Edge {
- uint32_t from;
- uint32_t to;
- uint32_t weight;
- Edge(uint32_t from, uint32_t to, uint32_t weight = 0) :
- from(from), to(to), weight(weight){}
- };
- bool operator<(const Edge& lhs, const Edge& rhs) {
- return lhs.weight < rhs.weight;
- }
- std::vector<Edge> GetMST(const std::vector<std::vector<Edge>>& graph) {
- const uint32_t INF = 101;
- const uint32_t verNum = graph.size();
- std::vector<uint32_t> distances(verNum, INF);
- std::vector<int64_t> predcessors(verNum, -1);
- std::vector<Edge> MST;
- std::priority_queue<std::pair<uint32_t, uint32_t>, std::vector<std::pair<uint32_t, uint32_t>>, std::greater<std::pair<uint32_t, uint32_t>>> queue;
- distances[0] = 0;
- //predcessors[0] = 0;
- queue.push({0, 0});
- while (!queue.empty()) {
- auto distAndVertex = queue.top();
- queue.pop();
- distances[distAndVertex.second] = 0;
- for (const auto& edge : graph[distAndVertex.second]) {
- if (distances[edge.to] > edge.weight) {
- distances[edge.to] = edge.weight;
- queue.push({edge.weight, edge.to});
- predcessors[edge.to] = distAndVertex.second;
- }
- }
- }
- for (uint32_t i = 0; i < verNum; ++i) {
- if (predcessors[i] != i) {
- MST.push_back(Edge(predcessors[i], i, distances[i]));
- }
- }
- return MST;
- }
- int main() {
- uint32_t verNum;
- std::cin >> verNum;
- std::vector<std::vector<Edge>> graph(verNum, std::vector<Edge>());
- uint32_t weight;
- for (uint32_t i = 0; i < verNum; ++i) {
- for (uint32_t j = 0; j < verNum; ++j) {
- std::cin >> weight;
- graph[i].push_back(Edge(i, j, weight));
- }
- }
- auto mst = GetMST(graph);
- uint32_t sum = 0;
- for (auto edge : mst) {
- //std::cout << edge.from << ' ' << edge.to << ' ' << edge.weight << '\n';
- sum += edge.weight;
- }
- std::cout << sum;
- //system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement