Pagini recente » Cod sursa (job #1624012) | Cod sursa (job #1383822) | Cod sursa (job #2397410) | Cod sursa (job #2600859) | Cod sursa (job #2960420)
// O(N*M^2)
#include <iostream>
#include <fstream>
#include <string.h>
#include <queue>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int NMAX = 1005;
int N, M, Graph[NMAX][NMAX], Father[NMAX], Total_Flow;
bool Seen[NMAX];
vector < int > Edges[NMAX];
int BFS()
{
int X, Flow = 0, bottleneck;
queue < int > Q;
memset(Seen, 0, sizeof(int) * (N + 1));
Q.push(1);
Seen[1] = 1;
while(!Q.empty())
{
X = Q.front();
Q.pop();
for(int newX : Edges[X])
{
if(newX == N)
continue;
if(!Seen[newX] && Graph[X][newX])
Q.push(newX), Seen[newX] = 1, Father[newX] = X;
}
}
for(int Node : Edges[N])
{
if(!Seen[Node])
continue;
X = Node;
// bottleneck = Graph[Father[X]][X];
bottleneck = Graph[X][N];
while(Father[X])
{
bottleneck = min(Graph[Father[X]][X], bottleneck);
X = Father[X];
}
Flow += bottleneck;
X = Node;
Graph[N][X] += bottleneck;
Graph[X][N] -= bottleneck;
while(Father[X])
{
Graph[X][Father[X]] += bottleneck;
Graph[Father[X]][X] -= bottleneck;
X = Father[X];
}
}
return Flow;
}
int main()
{
int x, y, c;
in >> N >> M;
for(int i = 1; i <= M; i++)
{
in >> x >> y >> c;
Edges[x].push_back(y);
Edges[y].push_back(x);
Graph[x][y] = c;
}
c = BFS();
while (c)
{
Total_Flow += c;
c = BFS();
}
out << Total_Flow;
return 0;
}