vadimk772336

Untitled

Dec 19th, 2021
877
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. using namespace std;
  4.  
  5. struct edge
  6. {
  7.     int idx;
  8.     int a;
  9.     int b;
  10.     int cost;
  11. };
  12.  
  13. struct vertex
  14. {
  15.     bool visited = false;
  16.     std::vector<struct edge> adj_list;
  17.     int count_edges = 0;
  18. };
  19.  
  20. void addEdge(int i, int j, int cost, vector<vertex>& vertexes)
  21. {
  22.     edge buff;
  23.  
  24.     buff.idx = j;
  25.     buff.edge_value = cost;
  26.  
  27.     vertexes[i].adj_list.push_back(buff);
  28.    
  29.     buff.idx = i;
  30.     vertexes[j].adj_list.push_back(buff);
  31.  
  32.     vertexes[i].count_edges++;
  33.     vertexes[j].count_edges++;
  34. }
  35.  
  36.  
  37. struct Compare
  38. {
  39.     bool operator()(edge& o1, edge& o2) const
  40.     {
  41.         return o1.cost > o2.cost;
  42.     }
  43. };
  44.  
  45. void showpq(priority_queue<struct edge, vector<struct edge>, Compare> gq)
  46. {
  47.     priority_queue<struct edge, vector<struct edge>, Compare> g = gq;
  48.     while (!g.empty())
  49.     {
  50.         cout << '\t' << g.top().cost;
  51.         g.pop();
  52.     }
  53.     cout << '\n';
  54. }
  55.  
  56. int main()
  57. {
  58.     priority_queue<struct edge, vector<struct edge>, Compare> heap;
  59.  
  60.     int n, m;
  61.     cin >> n >> m;
  62.    
  63.     int a,b,c;
  64.     vector<struct vertex> vertexes(n);
  65.     struct edge edge;
  66.  
  67.     for (int i = 0; i < m; ++i)
  68.     {
  69.         cin >> a >> b >> c;
  70.        
  71.         addEdge(a-1, b-1, cost, vertexes);
  72.        
  73.         if (a == 1 | b == 1)
  74.         {
  75.             edge.a = a;
  76.             edge.b = b;
  77.             edge.cost = cost;
  78.             heap.push(edge);
  79.         }
  80.     }
  81.  
  82.     visited[0] = true;
  83.     struct edge edge;
  84.     int new;
  85.     int max = 0;
  86.  
  87.     for (int i = 0; i < n; ++i)
  88.     {
  89.         edge = heap.pop();
  90.  
  91.         if (max < edge.cost)
  92.             max = edge.cost;
  93.  
  94.         if (visited[edge.a - 1])
  95.         {
  96.             new = edge.b - 1;
  97.             visited[new] = true;
  98.         }
  99.         else
  100.         {
  101.             new = edge.a - 1;
  102.             visited[new] = true;
  103.         }
  104.  
  105.         for (int j = 0; j < vertexes[new].count_edges; ++j)
  106.  
  107.             edge edge = vertexes[new].adj_list[j];
  108.  
  109.         if (not vertexes[edge.idx].visited)
  110.             heap.push(edge);
  111.     }
  112.  
  113.  
  114.     return 0;
  115. }
  116.  
Advertisement
Add Comment
Please, Sign In to add comment