Pagini recente » Cod sursa (job #2988128) | Cod sursa (job #1876178) | Cod sursa (job #2804908) | Cod sursa (job #3226517) | Cod sursa (job #1952234)
#include <cstring>
#include <fstream>
#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;
ifstream cin("maxflow.in");
cin.sync_with_stdio(false);
cin >> n >> m;
for (i = 1; i <= n; ++i)
L[i].reserve(MMAX);
for (i = 1; i <= m; ++i) {
cin >> 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() {
ofstream cout("maxflow.out");
cout << maxFlow << '\n';
}