Pagini recente » Cod sursa (job #396454) | Cod sursa (job #2761233) | Cod sursa (job #59156) | Cod sursa (job #850438) | Cod sursa (job #2211357)
#include<cstdio>
#include<vector>
#include<queue>
#define MAX_N 1000
#define oo 0x7fffffff
using namespace std;
vector<int>g[MAX_N+1];
int flow[MAX_N+1][MAX_N+1], c[MAX_N+1][MAX_N+1], p[MAX_N+1], n, m;
bool used[MAX_N+1];
inline int minim(int x, int y) {
if(x <= y) return x;
return y;
}
void readGraph() {
int i, x, y, cap;
FILE* fin = fopen("maxflow.in","r");
fscanf(fin,"%d%d",&n,&m);
for(i = 0; i < m; i++) {
fscanf(fin,"%d%d%d",&x,&y,&cap);
//printf("%d %d %d\n",x,y,cap);
g[x].push_back(y);
g[y].push_back(x);
c[x][y] = cap;
}
fclose(fin);
}
bool BFS(int s, int t) {
int i, node;
queue<int>q;
for(i = 1; i <= n; i++) {
p[i] = 0;
used[i] = false;
}
p[s] = -1;
used[s] = true;
q.push(s);
while(!q.empty()) {
node = q.front();
q.pop();
for(auto j : g[node]) {
if(!used[j] && c[node][j] - flow[node][j] > 0) {
used[j] = true;
p[j] = node;
q.push(j);
}
}
}
if(used[t])
return true;
return false;
}
int EdmondsKarp(int s, int t) {
int path_flow, i, maxFlow = 0;
while(BFS(s,t)) {
path_flow = oo;
for(i = t; i != s; i = p[i])
path_flow = minim(path_flow,c[p[i]][i] - flow[p[i]][i]);
for(i = t; i != s; i = p[i]) {
flow[p[i]][i] += path_flow;
flow[i][p[i]] -= path_flow;
}
maxFlow += path_flow;
}
return maxFlow;
}
void printFlow() {
FILE* fout = fopen("maxflow.out","w");
fprintf(fout,"%d\n",EdmondsKarp(1,n));
fclose(fout);
}
int main() {
readGraph();
printFlow();
return 0;
}