Pagini recente » Cod sursa (job #1816255) | Cod sursa (job #1206292) | Cod sursa (job #867180) | Cod sursa (job #1128665) | Cod sursa (job #903422)
Cod sursa(job #903422)
#include <cstdio>
#include <cstring>
#include <cassert>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
using namespace std;
typedef long long LL;
typedef vector<int>::iterator it;
const int oo = 0x3f3f3f3f;
const int MAX_N = 1005;
const int NIL = -1;
vector<int> G[MAX_N];
int N, Father[MAX_N], Solution;
int Capacity[MAX_N][MAX_N], Flow[MAX_N][MAX_N];
queue<int> Q;
void InitBFS(int Begin) {
memset(Father, NIL, sizeof(Father));
Father[Begin] = Begin;
Q.push(Begin);
}
bool BFS(int Begin, int End) {
for (InitBFS(Begin); !Q.empty(); Q.pop()) {
int X = Q.front();
if (X == End)
continue;
for (it Y = G[X].begin(); Y != G[X].end(); ++Y) {
if (Father[*Y] == NIL && Capacity[X][*Y] > Flow[X][*Y]) {
Father[*Y] = X;
Q.push(*Y);
}
}
}
return (Father[End] != NIL);
}
int MaximumFlow(int Source, int Sink) {
int MaxFlow = 0;
while (BFS(Source, Sink)) {
for (it Y = G[Sink].begin(); Y != G[Sink].end(); ++Y) {
if (Father[*Y] == NIL || Capacity[*Y][Sink] <= Flow[*Y][Sink])
continue;
Father[Sink] = *Y;
int CurrentFlow = oo;
for (int X = Sink; X != Source; X = Father[X])
CurrentFlow = min(CurrentFlow, Capacity[Father[X]][X] - Flow[Father[X]][X]);
for (int X = Sink; X != Source; X = Father[X]) {
Flow[Father[X]][X] += CurrentFlow;
Flow[X][Father[X]] -= CurrentFlow;
}
MaxFlow += CurrentFlow;
}
}
return MaxFlow;
}
void Solve() {
Solution = MaximumFlow(1, N);
}
inline void AddEdge(int X, int Y, int C) {
G[X].push_back(Y); G[Y].push_back(X);
Capacity[X][Y] = C; Capacity[Y][X] = 0;
}
void Read() {
assert(freopen("maxflow.in", "r", stdin));
int M; assert(scanf("%d %d", &N, &M) == 2);
for (; M > 0; --M) {
int X, Y, C; assert(scanf("%d %d %d", &X, &Y, &C) == 3);
AddEdge(X, Y, C);
}
}
void Print() {
assert(freopen("maxflow.out", "w", stdout));
printf("%d\n", Solution);
}
int main() {
Read();
Solve();
Print();
return 0;
}