Pagini recente » Cod sursa (job #751727) | Cod sursa (job #2749446) | Cod sursa (job #818053) | Cod sursa (job #1434212) | Cod sursa (job #1394071)
#include <stdio.h>
#include <vector>
#include <queue>
#define MAXN 1001
using namespace std;
int V, E;
vector <int> Gf[MAXN];
int c[MAXN][MAXN];
int s,t;
int f1[MAXN][MAXN];
int dist[MAXN];
int father[MAXN];
inline void readAndBuild() {
scanf("%d%d", &V, &E);
s = 1;
t = V;
int x, y, z;
for (int e = 0; e < E; ++ e) {
scanf("%d%d%d", &x, &y, &z);
if (c[y][x] == 0) {
Gf[x].push_back(y);
c[x][y] = z;
Gf[y].push_back(x);
} else {
c[x][y] = z;
}
}
}
inline bool bfs() {
queue <int> q;
q.push(s);
for (int i = 1; i <= V; ++ i) {
dist[i] = -1;
}
dist[s] = 0;
for (int node = q.front(); !q.empty(); node = q.front()) {
q.pop();
if (node == t) {
return true;
}
for (vector <int>::iterator it = Gf[node].begin(); it != Gf[node].end(); ++ it) {
if (dist[*it] == -1 && f1[node][*it] < c[node][*it]) {
dist[*it] = dist[node] + 1;
q.push(*it);
}
}
}
return false;
}
inline bool dfs(int node) {
if (node == t) return true;
bool foundBlockingFlow = false;
for (vector <int>::iterator it = Gf[node].begin(); it != Gf[node].end(); ++ it) {
if (father[*it] == -1 && dist[node] + 1 == dist[*it] && f1[node][*it] < c[node][*it]) {
father[*it] = node;
foundBlockingFlow = dfs(*it);
if (foundBlockingFlow) return true;
}
}
return false;
}
inline int maxFlowDinic() {
int maxFlow = 0;
for (bool sinkReached = bfs(); sinkReached; sinkReached = bfs()) {
for (int i = 1; i <= V; ++ i) {
father[i] = -1;
}
father[s] = 0;
for (bool existsBlckingFlow = dfs(s); existsBlckingFlow; existsBlckingFlow = dfs(s)) {
int cfpath = c[father[t]][t] - f1[father[t]][t];
for (int node = father[t]; node != s; node = father[node]) {
if (cfpath > c[father[node]][node] - f1[father[node]][node]) {
cfpath = c[father[node]][node] - f1[father[node]][node];
}
}
maxFlow += cfpath;
for (int node = t; node != s; node = father[node]) {
f1[father[node]][node] += cfpath;
f1[node][father[node]] -= cfpath;
}
for (int i = 1; i <= V; ++ i) {
father[i] = -1;
}
father[s] = 0;
}
}
return maxFlow;
}
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
readAndBuild();
int F = maxFlowDinic();
printf("%d\n", F);
return 0;
}