Pagini recente » Cod sursa (job #2187540) | Cod sursa (job #1591318) | Cod sursa (job #1723971) | Cod sursa (job #2210118) | Cod sursa (job #2211466)
#include<cstdio>
#include<vector>
#include<queue>
#define MAX_N 1000
#define oo 0x7fffffff
using namespace std;
vector<int>g[MAX_N+1];
int c[MAX_N+1][MAX_N+1], flow[MAX_N+1][MAX_N+1], p[MAX_N+1], n, m;
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);
c[x][y] = cap;
g[x].push_back(y);
g[y].push_back(x);
}
fclose(fin);
}
bool BFS(int s, int t) {
bool ok = false;
queue<int>q;
int node, i;
for(i = 1; i <= n; i++)
p[i] = 0;
p[s] = -1;
q.push(s);
while(!q.empty()) {
node = q.front();
q.pop();
for(auto i : g[node]) {
if(!p[i] && c[node][i] - flow[node][i] > 0) {
if(i != t) {
p[i] = node;
q.push(i);
} else ok = true;
}
}
}
return ok;
}
int Dinic(int s, int t) {
int path_flow, j, maxFlow = 0;
while(BFS(s,t)) {
for(auto i : g[t]) {
if(p[i] && c[i][t] - flow[i][t] > 0) {
p[t] = i;
path_flow = oo;
for(j = t; j != s; j = p[j])
path_flow = minim(path_flow,c[p[j]][j] - flow[p[j]][j]);
for(j = t; j != s; j = p[j]) {
flow[p[j]][j] += path_flow;
flow[j][p[j]] -= path_flow;
}
maxFlow += path_flow;
}
}
}
return maxFlow;
}
void printFlow() {
FILE* fout = fopen("maxflow.out","w");
fprintf(fout,"%d\n",Dinic(1,n));
fclose(fout);
}
int main() {
readGraph();
printFlow();
return 0;
}