Pagini recente » Cod sursa (job #473966) | Sandbox (cutiuţa cu năsip) | Cod sursa (job #2440954) | Cod sursa (job #1817685) | Cod sursa (job #2700246)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int N = 1001;
const int INF = 1 << 30;
int c[N][N], f[N][N], n, poz[N], nivel[N];
vector <int> a[N];
queue <int> q;
void init_nivel()
{
for (int i = 2; i <= n; i++)
{
nivel[i] = -1;
}
}
void init_poz()
{
for (int i = 1; i <= n; i++)
{
poz[i] = 0;
}
}
bool bfs()
{
init_nivel();
q.push(1);
while (!q.empty())
{
int x = q.front();
q.pop();
for (auto y: a[x])
{
if (c[x][y] == f[x][y]) continue;
if (nivel[y] != -1) continue;
nivel[y] = 1 + nivel[x];
q.push(y);
}
}
return (nivel[n] != -1);
}
int dfs(int x, int valf)
{
if (x == n)
{
return valf;
}
while (poz[x] < (int)a[x].size())
{
int y = a[x][poz[x]++];
if (nivel[y] != 1 + nivel[x] || f[x][y] == c[x][y])
{
continue;
}
int f_curent = dfs(y, min(valf, c[x][y] - f[x][y]));
if (f_curent != 0)
{
f[x][y] += f_curent;
f[y][x] -= f_curent;
return f_curent;
}
}
return 0;
}
int flux()
{
int f = 0;
while (bfs())
{
int f_curent;
init_poz();
while ((f_curent = dfs(1, INF)) != 0)
{
f += f_curent;
}
}
return f;
}
int main()
{
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, cap;
in >> x >> y >> cap;
c[x][y] = cap;
a[x].push_back(y);
a[y].push_back(x);//muchie de intoarcere
}
in.close();
out << flux();
out.close();
return 0;
}