Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define INF 0x3f3f3f3f
- using namespace std;
- ifstream fin("maxflow.in");
- ofstream fout("maxflow.out");
- int N;
- vector < vector < int > > Capacity, Graph;
- inline void min_self(int& a, int b) {
- a = min(a, b);
- }
- bool BFS(int source, int sink, vector < int >& parent) {
- parent.assign(N + 1, -1);
- parent[source] = -2;
- queue < int > Q;
- Q.emplace(source);
- while(!Q.empty()) {
- int curr = Q.front();
- Q.pop();
- for(int next : Graph[curr])
- if(parent[next] == -1 && Capacity[curr][next]) {
- parent[next] = curr;
- if(next == sink)
- return true;
- Q.emplace(next);
- }
- }
- return false;
- }
- int max_flow(int source, int sink) {
- int flow = 0;
- vector < int > parent;
- while(BFS(source, sink, parent))
- for(int prev : Graph[sink])
- if(parent[prev] != -1 && Capacity[prev][sink]) {
- parent[sink] = prev;
- int new_flow = INF;
- for(int node = sink; node != source; node = parent[node])
- min_self(new_flow, Capacity[parent[node]][node]);
- if(new_flow == 0)
- continue;
- flow += new_flow;
- for(int node = sink; node != source; node = parent[node]) {
- Capacity[parent[node]][node] -= new_flow;
- Capacity[node][parent[node]] += new_flow;
- }
- }
- return flow;
- }
- int main() {
- fin.sync_with_stdio(false);
- fout.sync_with_stdio(false);
- fin.tie(nullptr);
- fout.tie(nullptr);
- int M;
- fin >> N >> M;
- Capacity = vector < vector < int > >(N + 1, vector < int >(N + 1));
- Graph.resize(N + 1);
- while(M--) {
- int u, v, capacity;
- fin >> u >> v >> capacity;
- Capacity[u][v] = capacity;
- Graph[u].emplace_back(v);
- Graph[v].emplace_back(u);
- }
- fout << max_flow(1, N);
- }
Advertisement
Add Comment
Please, Sign In to add comment