Pagini recente » Cod sursa (job #1706707) | Cod sursa (job #41383) | Cod sursa (job #2219724) | Cod sursa (job #389495) | Cod sursa (job #2700786)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int dim = 1005;
const int M = 5005;
const int INF = 1e9 + 9;
struct muchie
{
int x, y, capacitate, flux;
};
muchie e[2*M];
vector<int> vec[dim];
int n,m,nr,parent[dim],sursa,destinatie;
void Adauga(int x,int y,int c)
{
e[nr] = (muchie){x,y,c,0};
vec[x].push_back(nr++);
e[nr] = (muchie){x,y,0,0};
vec[y].push_back(nr++);
}
int BFS()
{
queue<pair<int,int> > q;
for (int i=2; i<=n; i++)
{
parent[i] = -1;
}
q.push({1, INF});
while (!q.empty())
{
int x = q.front().first;
int flow = q.front().second;
q.pop();
for (auto y:vec[x])
{
muchie xy = e[y];
if (xy.flux < xy.capacitate && parent[xy.y] == -1)
{
parent[xy.y] = y;
flow = min(flow, xy.capacitate - xy.flux);
q.push({xy.y, flow});
if (xy.y == destinatie) return flow;
}
}
}
return 0;
}
void Actualizare(int flux)
{
int x = destinatie;
while (x != sursa)
{
int p = parent[x];
e[p].flux += flux;
e[(p^1)].flux -= flux;
x = e[p].x;
}
}
int MaxFlow()
{
int flow = 0, flow_cur;
while ((flow_cur = BFS()) != 0)
{
flow += flow_cur;
Actualizare(flow_cur);
}
return flow;
}
int main()
{
in >> n >> m;
sursa = 1;
destinatie = n;
for (int i=1,x,y,c; i<=m; i++)
{
in >> x >> y >> c;
Adauga(x,y,c);
}
out << MaxFlow();
return 0;
}