Pagini recente » Cod sursa (job #1265239) | Borderou de evaluare (job #1594511) | Borderou de evaluare (job #1217928) | Cod sursa (job #2585992) | Cod sursa (job #3329962)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/*
4 5
1 2 3
1 3 5
2 4 6
3 4 4
3 2 3
*/
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
const int NMAX = 1001;
int n, m;
vector<vector<int>> edgIn, edgOut;
vector<int> tata;
int cap[NMAX][NMAX], flux[NMAX][NMAX];
bool BFS(int s, int t){
queue<int> q;
vector<int> viz(n+1, 0);
tata.resize(n + 1, 0);
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
for(auto &v : edgOut[u]){
if(!viz[v] && cap[u][v] - flux[u][v] > 0){
viz[v] = 1;
q.push(v);
tata[v] = u;
if(v == t)
return true;
}
}
for(auto &v : edgIn[u]){
if(!viz[v] && flux[v][u] > 0){
viz[v] = 1;
q.push(v);
tata[v] = -u;
if(v == t)
return true;
}
}
}
return false;
}
int capRezid(int s, int t, vector<int> &tata){
int mn = 200000;
for(int v = t; v != s; v = abs(tata[v])){
if(tata[v] > 0){
mn = min(mn, cap[tata[v]][v] - flux[tata[v]][v]);
} else {
mn = min(mn, flux[v][-tata[v]]);
}
}
return mn;
}
void actualizareFlux(int s, int t, int cr, vector<int> &tata){
for(int v = t; v != s; v = abs(tata[v])){
if(tata[v] > 0){
flux[tata[v]][v] += cr;
} else {
flux[v][-tata[v]] -= cr;
}
}
}
int main() {
cin >> n >> m;
edgIn.resize(n);
edgOut.resize(n);
while(m--){
int x, y, z;
cin >> x >> y >> z;
edgOut[x].push_back(y);
edgIn[y].push_back(x);
cap[x][y] = z;
}
int fluxmax = 0;
while(BFS(1, n)){
int cr = capRezid(1,n,tata);
actualizareFlux(1, n, cr, tata);
fluxmax += cr;
}
cout << fluxmax;
return 0;
}