Pagini recente » Cod sursa (job #411588) | Cod sursa (job #1934451) | Cod sursa (job #423151) | Cod sursa (job #1364251) | Cod sursa (job #3040988)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
#define NMAX 1005
#define INF ((1<<30)-1)
int n, m, flow[NMAX][NMAX], cap[NMAX][NMAX], tata[NMAX], flow_max;
vector<int> G[NMAX];
bitset<NMAX> viz;
queue<int> q;
void citire() {
f >> n >> m;
int x, y, c;
for (int i = 0; i < m; ++i) {
f >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x);
cap[x][y] = c;
}
}
void element_nou(int x) {
if (x == n)
return;
for (auto &nod: G[x])
if (!viz[nod] && flow[x][nod] < cap[x][nod]) {
tata[nod] = x;
viz.set(nod);
q.push(nod);
}
}
bool bfs() {
viz.reset();
q.push(1);
tata[1] = 0;
viz.set(1);
while (!q.empty()) {
int x = q.front();
q.pop();
element_nou(x);
}
return viz[n];
}
void calculare_flux_maxim() {
while (bfs())
for (auto &nod: G[n]) {
if (!viz[nod] || flow[nod][n] == cap[nod][n])
continue;
tata[n] = nod;
int flow_max_cur = INF;
for (int x = n; tata[x]; x = tata[x])
flow_max_cur = min(flow_max_cur, cap[tata[x]][x] - flow[tata[x]][x]);
if (!flow_max_cur)
continue;
for (int x = n; tata[x]; x = tata[x]) {
flow[tata[x]][x] += flow_max_cur;
flow[x][tata[x]] -= flow_max_cur;
}
flow_max += flow_max_cur;
}
}
int main() {
citire();
calculare_flux_maxim();
g << flow_max;
return 0;
}