Pagini recente » Cod sursa (job #2290657) | Cod sursa (job #387207) | Cod sursa (job #2976627) | Cod sursa (job #2829023) | Cod sursa (job #2745300)
#include <bits/stdc++.h>
#define nmax 1005
#define inf 1000000009
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
vector<int> lista[nmax];
int flow[nmax][nmax], capacity[nmax][nmax], pater[nmax];
int n,m;
bool bfs(int start, int fin){
queue<int> q;
for(int i=1; i<=n; i++){
pater[i] = -1;
}
pater[start] = 0;
q.push(start);
while(!q.empty()){
int nod = q.front();
q.pop();
for(auto neigh: lista[nod]){
if(pater[neigh] == -1 && capacity[nod][neigh] > flow[nod][neigh]){
pater[neigh] = nod;
q.push(neigh);
}
}
}
return pater[fin] != -1;
}
int max_flow(int s, int t){
int ma_flow = 0;
while(bfs(s, t)){
for(auto v: lista[t]){
int neck = capacity[v][t] - flow[v][t];
if(neck == 0) continue;
for(int u = v; pater[u]!=0; u = pater[u]){
neck = min(neck, capacity[pater[u]][u] - flow[pater[u]][u]);
}
flow[v][t] += neck;
flow[t][v] -= neck;
for(int u = v; pater[u]!=0; u = pater[u]){
flow[pater[u]][u] += neck;
flow[u][pater[u]] -= neck;
}
ma_flow += neck;
}
}
return ma_flow;
}
int main(){
in >> n;
in >> m;
for(int i=0; i<m; i++){
int x, y;
in >> x >> y;
if(!capacity[x][y] && !capacity[y][x]){
lista[x].push_back(y);
lista[y].push_back(x);
}
in >> capacity[x][y];
}
out << max_flow(1,n) << '\n';
return 0;
}