Pagini recente » Cod sursa (job #1182950) | Cod sursa (job #146575) | Cod sursa (job #2437089) | Cod sursa (job #1253330) | Cod sursa (job #771296)
Cod sursa(job #771296)
#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< pair<int, int> > bfs(int source, int dest) {
queue<int> toBeProc;
vector< pair <int, int> > path;
int parent[NMAX];
bool processed[NMAX];
for (int i = 1; i <= n; i++) {
processed[i] = false;
parent[i] = 0;
}
toBeProc.push(source);
processed[source] = true;
bool END = false;
while (!toBeProc.empty()) {
int el = toBeProc.front();
toBeProc.pop();
vector<int>::iterator it;
for (it = edg[el].begin(); it != edg[el].end(); it++) {
if (!processed[*it] && CapacRez(el, *it) > 0) {
parent[*it] = el;
processed[*it] = true;
toBeProc.push(*it);
if (*it == source) {
END = true;
break;
}
}
}
if (END == true) {
break;
}
}
int child;
while (parent[dest] != 0) {
child = dest;
dest = parent[dest];
path.push_back(make_pair(dest, child));
}
return path;
}
int get_min(int &cf, vector< pair<int, int> > path) {
cf = std::numeric_limits<int>::max();
vector< pair<int, int> >::iterator it;
for (it = path.begin(); it != path.end(); it++) {
int x = (*it).first, y = (*it).second;
if (cf > CapacRez(x, y)) {
cf = CapacRez(x, y);
}
}
}
void modify(int cf, vector< pair<int, int> > path) {
vector< pair<int, int> >::iterator it;
for (it = path.begin(); it != path.end(); it++) {
int x = (*it).first;
int y = (*it).second;
Flux[x][y] += cf;
Flux[y][x] = -Flux[x][y];
}
}
int EdmondsKarp() {
int cf;
int s = 0;
while (true) {
vector< pair<int, 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;
}