Pagini recente » Clasament dot-com2011 | Cod sursa (job #1114640) | Cod sursa (job #745064) | Cod sursa (job #239464) | Cod sursa (job #1953640)
#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];
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 (C[t][u] <= 0) 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 (C[v][u] <= 0) continue;
if (dst[v] + 1 != dst[u]) continue;
int actualFlow = DFS(u, min(C[v][u], flow));
if (actualFlow == 0) continue;
C[v][u] -= actualFlow;
C[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;
if (!C[a][b]) G[a].push_back(b);
if (!C[b][a]) 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;
}