Pagini recente » Cod sursa (job #2102515) | Cod sursa (job #2480523) | Cod sursa (job #342427) | Cod sursa (job #1103161) | Cod sursa (job #2700785)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int N = 1001;
const int M = 5001;
const int INF = 1 << 30;
struct muchie
{
int x, y, c, f;
};
muchie e[2*M];
vector <int> a[N];
int n, nr, pred[N];
void adauga(int x, int y, int c)
{
e[nr] = (muchie){x, y, c, 0};
a[x].push_back(nr++);
//muchia de intoarcere
e[nr] = (muchie){y, x, 0, 0};
a[y].push_back(nr++);
}
int bfs()
{
queue <pair <int, int> > q;
for (int i = 2; i <= n; i++)
{
pred[i] = -1;
}
q.push({1, INF});
while (!q.empty())
{
int x = q.front().first;
int f = q.front().second;
q.pop();
for (auto i: a[x])
{
muchie xy = e[i];
int y = xy.y;
if (xy.f < xy.c && pred[y] == -1)
{
f = min(f, xy.c - xy.f);
q.push({y, f});
pred[y] = i;
if (y == n)
{
return f;
}
}
}
}
return 0;
}
void actualizare(int fc)
{
int x = n;
while (x != 1)
{
int i = pred[x];
e[i].f += fc;
e[i^1].f -= fc;
x = e[i].x;
}
}
int flux()
{
int f = 0, fc;
while ((fc = bfs()) != 0)
{
f += fc;
actualizare(fc);
}
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, c;
in >> x >> y >> c;
adauga(x, y, c);
}
out << flux();
in.close();
out.close();
return 0;
}