Pagini recente » Cod sursa (job #3312229) | Cod sursa (job #1991929) | Cod sursa (job #1921173) | Cod sursa (job #733233) | Cod sursa (job #3337048)
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int N = 1e3, F = 1e5 + 1e4 + 1;
vector<int> lista_ad[N + 1];
int rf[N + 1][N + 1];
queue<int> q;
int parinte[N + 1];
bool vizitat[N + 1];
bool bfs(int s, int t, int n)
{
for (int i = 1; i <= n; i++)
{
vizitat[i] = false;
parinte[i] = 0;
}
vizitat[s] = true;
parinte[s] = 0;
q.push(s);
while (!q.empty())
{
int curent = q.front();
q.pop();
for (int x : lista_ad[curent])
{
int v = x;
if (!vizitat[v] && rf[curent][v] > 0)
{
vizitat[v] = true;
parinte[v] = curent;
q.push(v);
}
}
}
if (vizitat[t])
return true;
return false;
}
int flux_maxim(int s, int t, int n)
{
// gasim fluxul maxim in retea
int max_flow = 0;
// cat timp mai gasim un s-t drum f-nesaturat
while (bfs(s, t, n))
{
// parcurgem s-t drumul gasit si calculam minimul fluxului pe care putem
// sa il bagam
int nod = t, c_curent, c_drum = F + 1;
while (parinte[nod] != 0)
{
c_curent = rf[parinte[nod]][nod];
if (c_curent < c_drum)
c_drum = c_curent;
nod = parinte[nod];
}
// actualizam capacitatile reziduale
nod = t;
while (parinte[nod] != 0)
{
rf[parinte[nod]][nod] -= c_drum;
rf[nod][parinte[nod]] += c_drum;
nod = parinte[nod];
}
max_flow += c_drum;
}
return max_flow;
}
int main()
{
int n, m;
in >> n >> m;
int u, v, c;
for (int i = 0; i < m; i++)
{
in >> u >> v >> c;
lista_ad[u].push_back(v);
rf[u][v] = c;
}
out << flux_maxim(1, n, n);
return 0;
}