Advertisement
myloyo

7. Каркас (Краскала)

Dec 9th, 2024 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. void Task7() {
  2.         int n = this->CountVertices();
  3.         int m = this->CountEdges();
  4.         int i = 0;
  5.  
  6.         vector<pair<int, pair<string, string>>> edges;
  7.         for (auto it = AdjList.begin(); it != AdjList.end(); it++) {
  8.             for (auto jt = it->second.begin(); jt != it->second.end(); jt++) {
  9.                 if (it->first < jt->first) {
  10.                     edges.push_back(make_pair(jt->second, make_pair(it->first, jt->first)));
  11.                 }
  12.             }
  13.         }
  14.  
  15.         sort(edges.begin(), edges.end());
  16.         map<string, string> component;
  17.         for (auto& vertex : AdjList) {
  18.             component[vertex.first] = vertex.first;
  19.         }
  20.  
  21.         vector<pair<string, string>> res;
  22.         for (auto& edge : edges) {
  23.             string u = edge.second.first;
  24.             string v = edge.second.second;
  25.             int weight = edge.first;
  26.             if (component[u] != component[v]) {
  27.                 res.push_back(make_pair(u, v));
  28.                 string old_component = component[v];
  29.                 for (auto& pair : component) {
  30.                     if (pair.second == old_component) {
  31.                         pair.second = component[u];
  32.                     }
  33.                 }
  34.             }
  35.         }
  36.  
  37.         sort(res.begin(), res.end());
  38.         cout << "Остовное дерево" << endl;
  39.         for (auto& edge : res) {
  40.             cout << edge.first << " - " << edge.second << " (вес: " << AdjList[edge.first][edge.second] << ")" << endl;
  41.         }
  42.     }
  43.  
  44.  
  45. //main.cpp
  46.  
  47. #include <iostream>
  48. #include <string>
  49. #include <vector>
  50. #include <fstream>
  51. #include <vector>
  52. #include <list>
  53. #include <map>
  54. #include <locale>
  55. #include <windows.h>
  56. #include "Graph.h"
  57.  
  58. using namespace std;
  59.  
  60. int main() {
  61.     setlocale(LC_ALL, "Russian");
  62.     SetConsoleOutputCP(CP_UTF8);
  63.     map<string, Graph> graphs;
  64.  
  65.     string с = "prim3.txt";
  66.     Graph g;
  67.     g.loadFromFile(с);
  68.     graphs[с] = g;
  69.  
  70.     cout << "Задание 7\n";
  71.     g.Task7();
  72.     cout << "\n";
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement