Pagini recente » Cod sursa (job #1823263) | Cod sursa (job #3191182) | Cod sursa (job #3033541) | Cod sursa (job #513088) | Cod sursa (job #889798)
Cod sursa(job #889798)
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;
#define INFILE "maxflow.in"
#define OUTFILE "maxflow.out"
#define NMAX 1001
#define INF 0x3f3f3f3f
ifstream fin(INFILE);
ofstream fout(OUTFILE);
vector<int>::iterator it;
int n, maxflow;
vector<int> e[NMAX];
int cap[NMAX][NMAX], f[NMAX][NMAX], pre[NMAX], coada[NMAX];
bool vis[NMAX];
int bfs() {
// bfs from start to destination
memset(vis, 0, sizeof(vis));
coada[0] = 1;
vis[1] = 1;
pre[1] = -1;
for(int cd = 0, u = 0; cd<=u; cd++ ) {
int nod = coada[cd];
if( nod==n ) continue;
// pass all neighbours, add them to queue if not destination
for(it=e[nod].begin(); it!=e[nod].end(); it++)
// neighbour not visited and there is still capacity on edge
if( !vis[*it] && cap[nod][*it]>f[nod][*it] ) {
vis[*it] = 1;
pre[*it] = nod;
coada[++u] = *it;
}
}
// return if it is still possible to reach the destination
return vis[n];
}
int main() {
int m, a, b, c;
fin >> n >> m;
while(m--) {
fin >> a >> b >> c;
e[a].push_back(b);
e[b].push_back(a);
cap[a][b] += c;
}
for(maxflow = 0; bfs(); ) {
// traverse all nodes that can lead to destination
for(it=e[n].begin(); it!=e[n].end(); it++)
if( vis[*it] && cap[*it][n]>f[*it][n] ) {
int flow = INF;
for(int nod = n; nod!=1; nod = pre[nod])
flow = min(flow, cap[pre[nod]][nod] - f[pre[nod]][nod]);
if(!flow) continue;
maxflow += flow;
for(int nod = n; nod!=1; nod = pre[nod]) {
f[pre[nod]][nod] += flow;
f[nod][pre[nod]] -= flow;
}
}
}
fout << maxflow;
return 0;
}