Pagini recente » Cod sursa (job #3274142) | Cod sursa (job #90999) | Cod sursa (job #3222182) | Cod sursa (job #586107) | Cod sursa (job #2554289)
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int INF = 1e9+5;
struct muchie
{
int x, y, flow, cap;
muchie(int x, int y, int cap) : x(x), y(y), cap(cap) { flow=0; }
};
bool BFS();
int DFS(int nod, int flow);
int n, m, start, stop, niv[1005], ind[1005];
vector<int> L[1005];
vector<muchie> muchii;
int main()
{
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
cin >> n >> m;
start = 1; stop = n;
int nr = 0, x, y, c;
for (int i=1;i<=m;i++)
{
cin >> x >> y >> c;
muchii.emplace_back(x,y,c);
muchii.emplace_back(y,x,0);
L[x].push_back(nr);
L[y].push_back(nr+1);
nr += 2;
}
int ans = 0, flow;
while (BFS())
{
memset(ind,0,sizeof(ind));
while (flow = DFS(1,INF))
ans += flow;
}
cout << ans << '\n';
return 0;
}
bool BFS()
{
int in=0, sf=0, Q[1005];
Q[sf++] = start;
memset(niv,0,sizeof(niv));
niv[start] = 1;
while (in < sf)
{
int aux = Q[in++];
for (int i:L[aux])
{
if (!niv[muchii[i].y] && muchii[i].flow < muchii[i].cap)
{
niv[muchii[i].y] = niv[aux] + 1;
Q[sf++] = muchii[i].y;
}
}
}
return niv[stop] != 0;
}
int DFS(int nod, int flow)
{
if (!flow)
return 0;
if (nod == stop)
return flow;
for (;ind[nod]<L[nod].size();ind[nod]++)
{
int i = L[nod][ind[nod]];
muchie aux = muchii[i];
if (niv[aux.y] == niv[nod]+1 && aux.flow < aux.cap)
{
int transf = DFS(aux.y,min(flow,aux.cap-aux.flow));
if (transf)
{
muchii[i].flow += transf;
muchii[i^1].flow -= transf;
return transf;
}
}
}
return 0;
}