Pagini recente » Cod sursa (job #109129) | Cod sursa (job #2039030) | Cod sursa (job #666949) | Cod sursa (job #2772283) | Cod sursa (job #3290677)
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
#define cin f
#define cout g
vector<vector<int>> cap;
vector<vector<int>> adj;
vector<int> parent;
int n, m;
int flow_bfs(int s, int t){
parent.clear();
parent.resize(n+1, -1);
parent[s] = -2;
queue<pair<int,int>> q;
q.push({s, INT_MAX});
while(!q.empty()){
int nod = q.front().first;
int flow = q.front().second;
q.pop();
for(auto it : adj[nod]){
if(parent[it] == -1 && cap[nod][it]){
parent[it] = nod;
int new_flow = min(flow, cap[nod][it]);
if(it == t)
return new_flow;
q.push({it, new_flow});
}
}
}
return 0;
}
int maxflow(int s, int t){
int flow = 0;
int new_flow;
while(new_flow = flow_bfs(s, t)){
flow += new_flow;
int cur = t;
while(cur != s){
int prev = parent[cur];
cap[prev][cur] -= new_flow;
cap[cur][prev] += new_flow;
cur = prev;
}
}
return flow;
}
int main(){
cin >> n >> m;
adj.resize(n+1);
cap.resize(n+1, vector<int>(n+1));
for(int i = 1; i <= m; i ++){
int s, e, flow;
cin >> s >> e >> flow;
cap[s][e] = flow;
adj[s].push_back(e);
adj[e].push_back(s);
}
cout << maxflow(1, n);
return 0;
}