Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <queue>
  5.  
  6.  
  7. struct Edge {
  8.     uint32_t from;
  9.     uint32_t to;
  10.     uint32_t weight;
  11.  
  12.     Edge(uint32_t from, uint32_t to, uint32_t weight = 0) :
  13.         from(from), to(to), weight(weight){}
  14. };
  15.  
  16. bool operator<(const Edge& lhs, const Edge& rhs) {
  17.     return lhs.weight < rhs.weight;
  18. }
  19.  
  20. std::vector<Edge> GetMST(const std::vector<std::vector<Edge>>& graph) {
  21.     const uint32_t INF = 101;
  22.     const uint32_t verNum = graph.size();
  23.     std::vector<uint32_t> distances(verNum, INF);
  24.     std::vector<int64_t> predcessors(verNum, -1);
  25.     std::vector<Edge> MST;
  26.     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;
  27.     distances[0] = 0;
  28.     //predcessors[0] = 0;
  29.     queue.push({0, 0});
  30.     while (!queue.empty()) {
  31.         auto distAndVertex = queue.top();
  32.         queue.pop();
  33.         distances[distAndVertex.second] = 0;
  34.         for (const auto& edge : graph[distAndVertex.second]) {
  35.             if (distances[edge.to] > edge.weight) {
  36.                 distances[edge.to] = edge.weight;
  37.                 queue.push({edge.weight, edge.to});
  38.                 predcessors[edge.to] = distAndVertex.second;
  39.             }
  40.         }
  41.     }
  42.     for (uint32_t i = 0; i < verNum; ++i) {
  43.         if (predcessors[i] != i) {
  44.             MST.push_back(Edge(predcessors[i], i, distances[i]));
  45.         }
  46.     }
  47.     return MST;
  48. }
  49.  
  50.  
  51. int main() {
  52.     uint32_t verNum;
  53.     std::cin >> verNum;
  54.     std::vector<std::vector<Edge>> graph(verNum, std::vector<Edge>());
  55.     uint32_t weight;
  56.     for (uint32_t i = 0; i < verNum; ++i) {
  57.         for (uint32_t j = 0; j < verNum; ++j) {
  58.             std::cin >> weight;
  59.             graph[i].push_back(Edge(i, j, weight));
  60.         }
  61.     }
  62.     auto mst = GetMST(graph);
  63.     uint32_t sum = 0;
  64.     for (auto edge : mst) {
  65.         //std::cout << edge.from << ' ' << edge.to << ' ' << edge.weight << '\n';
  66.         sum += edge.weight;
  67.     }
  68.     std::cout << sum;
  69.  
  70.     //system("pause");
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement