Pagini recente » Cod sursa (job #1896938) | Cod sursa (job #2299951) | Cod sursa (job #1920941) | Cod sursa (job #1092616) | Cod sursa (job #3272272)
#include <climits>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
const int nMax = 1e3;
int n, m;
int capacity[nMax][nMax];
int flux[nMax][nMax];
std::vector<int> parent;
std::vector<std::vector<int>> graph;
std::bitset<nMax> vis;
int BFS(int source, int destination) {
vis.reset(); parent.assign(n, -1);
std::queue<int> q;
q.push(source); vis[source] = true;
while (!q.empty()) {
int currNode = q.front(); q.pop();
for (auto& next : graph[currNode]) {
if (vis[next] == false && capacity[currNode][next] - flux[currNode][next] > 0) {
q.push(next); vis[next] = true; parent[next] = currNode;
}
}
}
if (vis[destination] == false) {
return 0;
}
int flow = INT_MAX;
for (int node = destination; node != source; node = parent[node]) {
flow = std::min(flow, capacity[parent[node]][node] - flux[parent[node]][node]);
}
for (int node = destination; node != source; node = parent[node]) {
flux[parent[node]][node] += flow, flux[node][parent[node]] -= flow;
}
return flow;
}
int EdmondsKarp(int source, int destination) {
int maxFlow = 0;
while (int flow = BFS(source, destination)) {
maxFlow += flow;
}
return maxFlow;
}
int main() {
std::ifstream fin("maxflow.in");
std::ofstream fout("maxflow.out");
fin >> n >> m;
graph.assign(n, std::vector<int>());
for (int i = 0; i < m; i += 1) {
int u, v, c; fin >> u >> v >> c; u -= 1, v -= 1;
graph[u].emplace_back(v), graph[v].emplace_back(u);
capacity[u][v] = c;
}
fout << EdmondsKarp(0, n - 1);
graph.clear();
fin.close(), fout.close();
return 0;
}