Pagini recente » Cod sursa (job #1693575) | Cod sursa (job #2608935) | Cod sursa (job #270277) | Cod sursa (job #636787) | Cod sursa (job #1953629)
#include <cstdio>
#include <climits>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cassert>
#include <queue>
using namespace std;
#ifdef INFOARENA
#define ProblemName "maxflow"
#endif
#define MCONCAT(A, B) A B
#ifdef ProblemName
#define InFile MCONCAT(ProblemName, ".in")
#define OuFile MCONCAT(ProblemName, ".out")
#else
#define InFile "fis.in"
#define OuFile "fis.out"
#endif
typedef long long LL;
#define MAXN 1100
typedef vector< vector<int> > graph;
graph G;
int N;
int C[MAXN][MAXN], F[MAXN][MAXN];
int nedge[MAXN];
int dst[MAXN];
#define INFINIT 0x3F3F3F3F
queue<int> Q;
bool BFS(int s) {
memset(dst, 0x3F, sizeof(dst));
dst[s] = 0;
while (!Q.empty()) Q.pop();
Q.push(s);
while (!Q.empty()) {
int t = Q.front();
Q.pop();
for (const auto &u : G[t]) {
if (F[t][u] >= C[t][u]) continue;
if (dst[u] != INFINIT) continue;
dst[u] = dst[t] + 1;
Q.push(u);
}
}
return (dst[N - 1] != INFINIT);
}
int DFS(int v, int flow) {
if (v == (N - 1)) return flow;
for (; nedge[v] != G[v].size(); ++nedge[v]) {
int u = G[v][nedge[v]];
if (F[v][u] >= C[v][u]) continue;
if (dst[v] + 1 != dst[u]) continue;
int actualFlow = DFS(u, min(C[v][u] - F[v][u], flow));
if (actualFlow == 0) continue;
F[v][u] += actualFlow;
F[u][v] -= actualFlow;
return actualFlow;
}
return 0;
}
int blockingFlow() {
int totalFlow = 0;
memset(nedge, 0, sizeof(nedge));
int flow = 0;
while (flow = DFS(0, INFINIT)) totalFlow += flow;
return totalFlow;
}
int Dinic() {
int flow = 0;
while (BFS(0)) flow += blockingFlow();
return flow;
}
void input() {
int M;
scanf("%d%d", &N, &M);
G.resize(N);
for (int i = 0; i < M; ++i) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
--a, --b;
G[a].push_back(b);
G[b].push_back(a);
C[a][b] += c;
}
}
int main() {
freopen(InFile, "r", stdin);
freopen(OuFile, "w", stdout);
input();
printf("%d\n", Dinic());
return 0;
}