Pagini recente » Cod sursa (job #2915192) | Cod sursa (job #594070) | Cod sursa (job #2725117) | Cod sursa (job #1157921) | Cod sursa (job #2984146)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int INF = 0x3f3f3f3f;
const int SIZE = 1005;
vector <int> G[SIZE];
int n, m, capacity[SIZE][SIZE], parent[SIZE];
bool bfs(int s, int t)
{
memset(parent, 0, sizeof(parent));
queue <int> q;
q.push(s);
while (q.empty() == false)
{
int node = q.front();
q.pop();
for (unsigned int i = 0; i < G[node].size(); i++)
{
int neighbour = G[node][i];
if (parent[neighbour] == 0 && capacity[node][neighbour] > 0)
{
parent[neighbour] = node;
q.push(neighbour);
if (neighbour == t)
{
return true;
}
}
}
}
return false;
}
int MaxFlow(int source, int sink)
{
int maxFlow = 0, fmin;
while (bfs(source, sink))
for (auto x : G[sink])
{
if (parent[x] == 0 || capacity[x][sink] <= 0)
continue;
parent[sink] = x;
fmin = INF;
int node = sink;
while (node != source)
{
int par = parent[node];
fmin = min(fmin, capacity[par][node]);
node = par;
}
node = sink;
while (node != source)
{
int par = parent[node];
capacity[par][node] -= fmin;
capacity[node][par] += fmin;
node = par;
}
maxFlow += fmin;
}
return maxFlow;
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; ++i)
{
int x, y, z;
f >> x >> y >> z;
G[x].push_back(y);
G[y].push_back(x);
capacity[x][y] += z;
}
g << MaxFlow(1, n);
return 0;
}