Pagini recente » Cod sursa (job #458139) | Cod sursa (job #1328014) | Cod sursa (job #289397) | Cod sursa (job #573603) | Cod sursa (job #1952252)
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
#define NMAX 1010
#define MMAX 5010
#define INF 2000000000
using namespace std;
vector <int> L[NMAX];
queue <int> coada;
int n, m, capacity[NMAX][NMAX], parent[NMAX], maxFlow;
bool viz[NMAX];
void afisare();
void solve();
bool BFS();
void citire();
int main() {
citire();
solve();
afisare();
}
void citire() {
int i, a, b, c;
FILE *fin = fopen("maxflow.in", "r");
fscanf(fin, "%d %d\n", &n, &m);
//for (i = 1; i <= n; ++i)
//L[i].reserve(NMAX);
for (i = 1; i <= m; ++i) {
fscanf(fin, "%d %d %d\n", &a, &b, &c);
L[a].push_back(b);
L[b].push_back(a);
capacity[a][b] += c;
}
}
void solve() {
int flow, pathNode;
while (BFS()) {//cat timp mai gasesc un drum de ameliorare
for (auto adiacentNode : L[n]) {
if (!viz[adiacentNode] || !capacity[adiacentNode][n])
continue;
flow = INF;
for (pathNode = n; pathNode != 1; pathNode = parent[pathNode])
flow = min(flow, capacity[parent[pathNode]][pathNode]);
maxFlow += flow;
for (pathNode = n; pathNode != 1; pathNode = parent[pathNode]) {
capacity[parent[pathNode]][pathNode] -= flow;
capacity[pathNode][parent[pathNode]] += flow;
}
}
}
}
bool BFS() {
int currentNode;
memset(viz, 0, sizeof(viz));
while (!coada.empty()) coada.pop();
viz[1] = true; coada.push(1);
while (!coada.empty()) {
currentNode = coada.front(); coada.pop();
if (currentNode == n)
return true;
for (auto adiacentNode : L[currentNode])
if (!viz[adiacentNode] && capacity[currentNode][adiacentNode]) {
viz[adiacentNode] = true;
coada.push(adiacentNode);
parent[adiacentNode] = currentNode;
}
}
return false;
}
void afisare() {
FILE *fout = fopen("maxflow.out", "w");
fprintf(fout, "%d\n", maxFlow);
}