Pagini recente » Cod sursa (job #1820715) | Cod sursa (job #1740655) | Cod sursa (job #1619894) | Cod sursa (job #1588141) | Cod sursa (job #2889064)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const string filename = "maxflow";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");
const int maxN = 1005, inf = 0x3f3f3f3f;
int n, m, p[maxN], cap[maxN][maxN], flux[maxN][maxN], max_flow;
bool used[maxN];
vector <int> G[maxN];
queue <int> q;
bool bfs()
{
for(int i = 1; i <= n; i++)
used[i] = 0;
q.push(1);
used[1] = 1;
while(!q.empty())
{
int nod = q.front();
q.pop();
for(int vecin : G[nod])
{
if(used[vecin])
continue;
if(cap[nod][vecin] > flux[nod][vecin])
{
p[vecin] = nod;
used[vecin] = 1;
q.push(vecin);
}
}
}
return used[n];
}
int main()
{
fin >> n >> m;
for(int x, y, c, i = 1; i <= m; i++)
{
fin >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x);
cap[x][y] = c;
}
while(bfs())
{
for(int vecin : G[n])
{
if(cap[vecin][n] == flux[vecin][n])
continue;
if(!used[vecin])
continue;
p[n] = vecin;
int min_flow = inf;
for(int x = n; x != 1; x = p[x])
min_flow = min(min_flow, cap[p[x]][x] - flux[p[x]][x]);
for(int x = n; x != 1; x = p[x])
{
flux[p[x]][x] += min_flow;
flux[x][p[x]] -= min_flow;
}
max_flow += min_flow;
}
}
fout << max_flow;
return 0;
}