Pagini recente » Cod sursa (job #1292292) | Cod sursa (job #280150) | Cod sursa (job #2910414) | Cod sursa (job #1295061) | Cod sursa (job #1953564)
#include <cstdio>
#include <climits>
#include <algorithm>
#include <vector>
#include <cstring>
#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];
vector<int>::iterator 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 (auto &u = nedge[v]; u != G[v].end(); ++u) {
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;
for (int i = 0; i < N; ++i)
nedge[i] = G[i].begin();
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;
C[b][a] = 0;
F[a][b] = F[b][a] = 0;
}
}
int main() {
freopen(InFile, "r", stdin);
freopen(OuFile, "w", stdout);
input();
printf("%d\n", Dinic());
return 0;
}