Pagini recente » Cod sursa (job #191816) | Cod sursa (job #2388928) | Cod sursa (job #134109) | Cod sursa (job #1313985) | Cod sursa (job #1399340)
//Problem flux
#include <cassert>
#include <cmath>
#include <cstdint>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int MAX_N = 1005;
int N, M;
vector<int> graph[MAX_N];
int cap[MAX_N][MAX_N];
int flow[MAX_N][MAX_N];
int source, sink;
inline int cp(int a, int b) {
return cap[a][b] - flow[a][b];
}
bool findAugPath(vector<int> &father) {
fill(father.begin(), father.end(), 0);
queue<int> q;
q.push(source);
bool found = false;
while (!q.empty()) {
int node = q.front();
q.pop();
if (node == sink) {
found = true;
}
for (auto next: graph[node]) {
if (father[next] == 0 && cp(node, next) > 0) {
father[next] = node;
q.push(next);
}
}
}
return found;
}
int maxflow() {
int result = 0;
vector<int> father(N + 1, 0);
while (findAugPath(father)) {
for (auto node: graph[sink]) {
if (!father[node]) continue;
int newFlow = cp(node, sink);
for (int v = node; v != source && newFlow; v = father[v]) {
newFlow = min(newFlow, cp(father[v], v));
}
if (newFlow == 0) continue;
flow[node][sink] += newFlow;
flow[sink][node] -= newFlow;
for (int v = node; v != source; v = father[v]) {
flow[father[v]][v] += newFlow;
flow[v][father[v]] -= newFlow;
}
result += newFlow;
}
}
return result;
}
void readin() {
fin >> N >> M;
for (int i = 1, a, b, c; i <= M; i += 1) {
fin >> a >> b >> c;
graph[a].push_back(b);
graph[b].push_back(a);
cap[a][b] = c;
}
source = 1;
sink = N;
}
int main() {
readin();
fout << maxflow();
return 0;
}