Pagini recente » Cod sursa (job #3225631) | Cod sursa (job #3219806) | Cod sursa (job #2054946) | Cod sursa (job #2683847) | Cod sursa (job #771305)
Cod sursa(job #771305)
#include <stdio.h>
#include <vector>
#include <queue>
#include <limits>
#define NMAX 1002
#define MMAX 5002
using namespace std;
vector<int> edg[NMAX];
int Capac[NMAX][NMAX];
int Flux[NMAX][NMAX];
int n;
int CapacRez(int x, int y) {
return (Capac[x][y] - Flux[x][y]);
}
vector<int> bfs(int source, int dest) {
queue<int> toBeProc;
vector<int> path;
int parent[NMAX];
memset(parent, 0, sizeof(parent));
toBeProc.push(source);
parent[source] = -1;
while (!toBeProc.empty()) {
int el = toBeProc.front();
toBeProc.pop();
vector<int>::iterator it;
for (it = edg[el].begin(); it != edg[el].end(); it++) {
if (parent[*it] == 0 && CapacRez(el, *it) > 0) {
parent[*it] = el;
toBeProc.push(*it);
}
}
if (el == dest) {
break;
}
}
if (parent[dest] == 0) {
return path;
}
int child;
while (dest != -1) {
path.push_back(dest);
dest = parent[dest];
}
return path;
}
void get_min(int &cf, vector<int> path) {
cf = std::numeric_limits<int>::max();
vector<int>::iterator it;
for (it = path.begin(); (it + 1) != path.end(); it++) {
int y = *it;
int x = *(it + 1);
if (cf > CapacRez(x, y)) {
cf = CapacRez(x, y);
}
}
}
void modify(int cf, vector<int> path) {
vector<int>::iterator it;
for (it = path.begin(); (it + 1) != path.end(); it++) {
int y = *it;
int x = *(it + 1);
Flux[x][y] += cf;
Flux[y][x] = -Flux[x][y];
}
}
void EdmondsKarp() {
int cf;
int s = 0;
while (true) {
vector<int> path = bfs(1, n);
if (path.empty()) {
break;
}
get_min(cf, path);
modify(cf, path);
s += cf;
}
printf("%d", s);
}
void read_() {
int m, s, d, c;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &s, &d, &c);
edg[s].push_back(d);
Capac[s][d] = c;
}
}
int main() {
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
read_();
EdmondsKarp();
return 0;
}