Pagini recente » Cod sursa (job #567283) | Cod sursa (job #819054) | Cod sursa (job #2546342) | Cod sursa (job #1861496) | Cod sursa (job #2652983)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int INF = 0x3f3f3f3f3f3f3f3f;
int N, M, maxFlow;
int cap[1010][1010], flow[1010][1010], father[1010];
bool use[1010];
vector<vector<int>> adj;
bool BFS()
{
memset(father, 0, sizeof father);
memset(use, false, sizeof use);
queue<int> q;
q.push(1);
use[1] = true;
while(!q.empty())
{
int node = q.front();
q.pop();
if(node == N)
continue;
for(auto i : adj[node])
{
if(!use[i] && (cap[node][i] - flow[node][i] > 0))
{
use[i] = true;
father[i] = node;
q.push(i);
}
}
}
return use[N];
}
int main()
{
in >> N >> M;
adj.resize(N + 5);
for(int i = 1; i <= M; i++)
{
int x, y, c;
in >> x >> y >> c;
adj[x].push_back(y);
adj[y].push_back(x);
cap[x][y] = c;
if(cap[y][x] != 0)
continue;
cap[y][x] = c;
flow[y][x] = c;
}
while(BFS())
{
for(auto node : adj[N])
{
if(use[node] && (cap[node][N] - flow[node][N]))
{
father[N] = node;
int bottleNeck = INF;
for(int i = N; i != 1; i = father[i])
bottleNeck = min(bottleNeck, cap[father[i]][i] - flow[father[i]][i]);
for(int i = N; i != 1; i = father[i])
{
flow[father[i]][i] += bottleNeck;
flow[i][father[i]] -= bottleNeck;
}
maxFlow += bottleNeck;
}
}
}
out << maxFlow << '\n';
return 0;
}