Pagini recente » Cod sursa (job #1912163) | Cod sursa (job #1106824) | Cod sursa (job #723242) | Cod sursa (job #320768) | Cod sursa (job #2595821)
#include <bits/stdc++.h>
#define MAX 1000
#define INF 1000000000
using namespace std;
vector<int>graph[MAX + 5];
int cap[MAX + 5][MAX + 5], flow[MAX + 5][MAX + 5], dist[MAX + 5];
bool bfs(int source, int destination, int n)
{
for(int i = 1; i <= n; i++)
dist[i] = n + 10;
dist[source] = 0;
queue<int>Q;
Q.push(source);
while(Q.size())
{
int nod = Q.front();
Q.pop();
for(auto vecin : graph[nod])
if(cap[nod][vecin] > flow[nod][vecin] && dist[vecin] > dist[nod] + 1)
{
dist[vecin] = dist[nod] + 1;
Q.push(vecin);
}
}
return dist[destination] != n + 10;
}
int maxFlow(int nod, int destination, int maximumFlow)
{
if(maximumFlow == 0 )return 0;
if(nod == destination)return maximumFlow;
int totalFlow = 0;
for(auto vecin : graph[nod])
{
if(dist[vecin] != dist[nod] + 1)continue;
int currentFlow = maxFlow(vecin, destination, min(maximumFlow - totalFlow, cap[nod][vecin] - flow[nod][vecin]));
flow[nod][vecin] += currentFlow;
flow[vecin][nod] -= currentFlow;
totalFlow += currentFlow;
}
return totalFlow;
}
int main()
{
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
ios::sync_with_stdio();
fin.tie(0);
fout.tie(0);
int n, m;
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, cost;
fin >> x >> y >> cost;
graph[x].push_back(y);
graph[y].push_back(x);
cap[x][y] += cost;
}
int sol = 0;
while(bfs(1, n, n))
sol += maxFlow(1, n, INF);
fout << sol;
fin.close();
fout.close();
return 0;
}