Pagini recente » Cod sursa (job #2785008) | Cod sursa (job #2978064) | Cod sursa (job #414933) | Cod sursa (job #1761064) | Cod sursa (job #3227598)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int min(int a, int b) {
return a<b ? a : b;
}
int bfs(int s, int t, vector<vector<int>> &adj, vector<vector<long long>> &capacity, vector<int> &parent) {
for(int i=1; i<=t; i++) {
parent[i]=-1;
}
parent[s]=-2;
queue<pair<int, int>> q;
q.push({s, 999999});
while(!q.empty()) {
int cur=q.front().first;
int flow=q.front().second;
q.pop();
for(auto next : adj[cur]) {
if(parent[next]==-1 && capacity[cur][next]) {
parent[next]=cur;
int new_flow=min(flow, capacity[cur][next]);
if(next==t) {
return new_flow;
}
q.push({next, new_flow});
}
}
}
return 0;
}
long long flow(int s, int t, vector<vector<int>> &adj, vector<vector<long long>> &capacity) {
long long maxflow=0;
vector<int> parent(t+1);
int new_flow;
do {
new_flow=bfs(s, t, adj, capacity, parent);
if(new_flow==0) {
return maxflow;
}
maxflow+=new_flow;
int cur=t;
while(cur!=s) {
int prev=parent[cur];
capacity[prev][cur]-=new_flow;
capacity[cur][prev]+=new_flow;
cur=prev;
}
}while(new_flow!=0);
return maxflow;
}
int main() {
int n, m;
fin >> n >> m;
vector<vector<int>> adj(n+1);
vector<vector<long long>> capacity(n+1, vector<long long>(n+1));
for(int i=0; i<m; i++) {
int u, v, cap;
fin >> u >> v >> cap;
adj[u].push_back(v);
capacity[u][v]=cap;
}
fout << flow(1, n, adj, capacity);
return 0;
}