Pagini recente » Cod sursa (job #1651759) | Cod sursa (job #1584322) | Cod sursa (job #2723394) | Cod sursa (job #1067685) | Cod sursa (job #879584)
Cod sursa(job #879584)
#include <fstream>
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
#define MAXN 2100
#define INF 0x3f3f3f3f
int N, M, capacitate[MAXN][MAXN], flux[MAXN][MAXN], dad[MAXN], used[MAXN];
vector<int> graph[MAXN];
bool BFS(int nod) {
if (nod == N)
return 1;
used[nod] = 1;
int start = rand() % (graph[nod].size() - 1);
int i = start;
do {
++i;
if (i == graph[nod].size())
i = 0;
int node = graph[nod][i];
if (!used[node] && capacitate[nod][node] > flux[nod][node]) {
dad[node] = nod;
if(BFS(node))
return 1;
}
} while (i != start);
return 0;
}
int main() {
fin >> N >> M;
for (int i = 1; i <= M; ++i) {
int x, y, c;
fin >> x >> y >> c;
graph[x].push_back(y); graph[y].push_back(x);
capacitate[x][y] = c;
capacitate[y][x] = 0;
}
int maxflow = 0;
while (BFS(1)) {
int minim = INF;
memset(used, 0, sizeof(used));
for (int nod = N; nod != 1; nod = dad[nod])
minim = min (minim, capacitate[dad[nod]][nod] - flux[dad[nod]][nod]);
maxflow += minim;
for (int nod = N; nod != 1; nod = dad[nod]) {
flux[dad[nod]][nod] += minim;
flux[nod][dad[nod]] -= minim;
}
}
fout << maxflow;
return 0;
}