Pagini recente » Cod sursa (job #2362385) | Cod sursa (job #1812891) | Cod sursa (job #111729) | Cod sursa (job #1126752) | Cod sursa (job #880314)
Cod sursa(job #880314)
#include <fstream>
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
#define MAXN 1100
#define INF 0x3f3f3f3f
int N, M, flux[MAXN][MAXN], dad[MAXN], used[MAXN];
vector<int> graph[MAXN];
bool DFS() {
memset(used, 0, sizeof(used));
int coada[MAXN];
coada[0] = 1; coada[1] = 1; used[1] = 1;
while (coada[0]) {
int poz = (rand() % coada[0]) + 1;
int nod = coada[poz];
coada[poz] = coada[coada[0]--];
if (nod == N)
return 1;
for (int i = 0; i < graph[nod].size(); ++i) {
int node = graph[nod][i];
if (!used[node] && flux[nod][node]) {
used[node] = 1;
dad[node] = nod;
coada[++coada[0]] = node;
}
}
}
return 0;
}
int main() {
fin >> N >> M;
srand(time(NULL));
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);
flux[x][y] = c;
}
int maxflow = 0;
while (DFS()) {
int minim = INF;
for (int nod = N; nod != 1; nod = dad[nod])
minim = min (minim, 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 << "\n";
return 0;
}