Pagini recente » Info Oltenia 2019 Proba pe Echipe Clasele 9 - 10 | Cod sursa (job #910514) | Cod sursa (job #2443225) | Cod sursa (job #3252740) | Cod sursa (job #2471497)
//Edmonds-Karp
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
const int NMAX = 1005;
int nodes, edges;
int residual_graph[NMAX][NMAX];
vector <int> graph[NMAX];
int father[NMAX];
bool bfs()
{
fill(father + 1, father + nodes + 1, 0);
queue <int> q;
q.push(1);
father[1] = -1;
while (!q.empty())
{
int node = q.front();
q.pop();
for (auto &next : graph[node])
if (father[next] == 0 && residual_graph[node][next] > 0)
{
father[next] = node;
q.push(next);
if (next == nodes)
return true;
}
}
return false;
}
int main()
{
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
fin >> nodes >> edges;
for (int i = 1;i <= edges;++i)
{
int u, v, c;
fin >> u >> v >> c;
graph[u].push_back(v);
graph[v].push_back(u);
residual_graph[u][v] += c;
}
int maxflow = 0;
while (bfs())
{
int mn = (1 << 30);
int now = nodes, u, v;
while (father[now] != -1)
{
u = father[now];
v = now;
mn = min(mn, residual_graph[u][v]);
now = father[now];
}
now = nodes;
while (father[now] != -1)
{
u = father[now];
v = now;
residual_graph[u][v] -= mn;
residual_graph[v][u] += mn;
now = father[now];
}
maxflow += mn;
}
fout << maxflow << "\n";
fin.close();
fout.close();
return 0;
}