Advertisement
TimSenin

Untitled

Oct 10th, 2022
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. struct Edge {
  4.     Edge(int from, int to, int capacity, int flow) : from(from), to(to), capacity(capacity), flow(flow) {}
  5.  
  6.     int from;
  7.     int to;
  8.     int capacity;
  9.     int flow;
  10. };
  11.  
  12. class Graph {
  13. public:
  14.     Graph(int n, int s, int f) {
  15.         vert_to_edge.resize(n + 1);
  16.         visited.resize(n + 1, false);
  17.         start = s;
  18.         finish = f;
  19.     }
  20.    
  21.     int dfs(int now, int curr_flow) {
  22.         if (now == finish) { return curr_flow; }
  23.         visited[now] = true;
  24.         for (int edge_ind : vert_to_edge[now]) {
  25.             Edge curr_edge = edges[edge_ind];
  26.             if (!visited[curr_edge.to] && curr_edge.capacity > 0) {
  27.                 int delta = dfs(curr_edge.to, std::min(curr_flow, curr_edge.capacity));
  28.                 if (delta > 0) {
  29.                     edges[edge_ind].capacity -= delta;
  30.                     edges[edge_ind + 1].capacity += delta;  // меняем обратное ребро
  31.                     return delta;
  32.                 }
  33.             }
  34.         }
  35.         return 0;
  36.     };
  37.  
  38.     void FordFulkerson() {
  39.         while (true) {
  40.             visited.assign(visited.size(), false);
  41.             int delta = dfs(start, 1e9);
  42.             if (delta > 0) {
  43.                 max_flow += delta;
  44.             } else {
  45.                 break;
  46.             }
  47.         }
  48.     };
  49.  
  50. public:
  51.     std::vector<std::vector<int>> vert_to_edge;  // TODO сделать правильные размеры всего
  52.     std::vector<Edge> edges;  // ребра индексируются с 0
  53.     std::vector<bool> visited;
  54.     int start;
  55.     int finish;
  56.     int edge_index = 0;
  57.     int max_flow = 0;
  58. };
  59.  
  60.  
  61. int main() {
  62.     int n, m;
  63.     std::cin >> n >> m;
  64.     Graph graph(n, 1, n);
  65.     for (int i = 0; i < m; ++i) {
  66.         int first, second, capacity;
  67.         std::cin >> first >> second >> capacity;
  68.         graph.vert_to_edge[first].push_back(graph.edge_index);
  69.         ++graph.edge_index;
  70.         graph.vert_to_edge[second].push_back(graph.edge_index);
  71.         ++graph.edge_index;
  72.         graph.edges.emplace_back(first, second, capacity, 0);
  73.         graph.edges.emplace_back(second, first, 0, 0);
  74.     }
  75.     graph.FordFulkerson();
  76.     std::cout << graph.max_flow;
  77.     return 0;
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement