Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- struct Edge {
- Edge(int from, int to, int capacity, int flow) : from(from), to(to), capacity(capacity), flow(flow) {}
- int from;
- int to;
- int capacity;
- int flow;
- };
- class Graph {
- public:
- Graph(int n, int s, int f) {
- vert_to_edge.resize(n + 1);
- visited.resize(n + 1, false);
- start = s;
- finish = f;
- }
- int dfs(int now, int curr_flow) {
- if (now == finish) { return curr_flow; }
- visited[now] = true;
- for (int edge_ind : vert_to_edge[now]) {
- Edge curr_edge = edges[edge_ind];
- if (!visited[curr_edge.to] && curr_edge.capacity > 0) {
- int delta = dfs(curr_edge.to, std::min(curr_flow, curr_edge.capacity));
- if (delta > 0) {
- edges[edge_ind].capacity -= delta;
- edges[edge_ind + 1].capacity += delta; // меняем обратное ребро
- return delta;
- }
- }
- }
- return 0;
- };
- void FordFulkerson() {
- while (true) {
- visited.assign(visited.size(), false);
- int delta = dfs(start, 1e9);
- if (delta > 0) {
- max_flow += delta;
- } else {
- break;
- }
- }
- };
- public:
- std::vector<std::vector<int>> vert_to_edge; // TODO сделать правильные размеры всего
- std::vector<Edge> edges; // ребра индексируются с 0
- std::vector<bool> visited;
- int start;
- int finish;
- int edge_index = 0;
- int max_flow = 0;
- };
- int main() {
- int n, m;
- std::cin >> n >> m;
- Graph graph(n, 1, n);
- for (int i = 0; i < m; ++i) {
- int first, second, capacity;
- std::cin >> first >> second >> capacity;
- graph.vert_to_edge[first].push_back(graph.edge_index);
- ++graph.edge_index;
- graph.vert_to_edge[second].push_back(graph.edge_index);
- ++graph.edge_index;
- graph.edges.emplace_back(first, second, capacity, 0);
- graph.edges.emplace_back(second, first, 0, 0);
- }
- graph.FordFulkerson();
- std::cout << graph.max_flow;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement