Pagini recente » Cod sursa (job #572835) | Cod sursa (job #384926) | Cod sursa (job #40317) | Cod sursa (job #150340) | Cod sursa (job #1602916)
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1000;
const int MMAX = 5000;
const int INF = 0x7fffffff;
int n; int m;
vector< vector<int> > g(NMAX + 1, vector<int>(0));
int capacity[NMAX + 1][NMAX + 1];
int flow[NMAX + 1][NMAX + 1];
vector<int> previous(NMAX + 1);
int solution;
void read() {
fin >> n >> m;
for(int i = 1; i <= m ;++i) {
int x; int y; int cap;
fin >> x >> y >> cap;
capacity[x][y] = cap;
g[x].push_back(y);
g[y].push_back(x);
}
}
bool findPaths(int start, int dest, vector< vector<int> >& g) {
queue<int> q;
bitset<NMAX + 1> vis;
q.push(start);
vis[start] = true;
previous[start] = start;
while(q.empty() == false) {
int node = q.front();
q.pop();
for(int x : g[node]) {
if(vis[x] == false && capacity[node][x] > flow[node][x]) {
vis[x] = true;
if(x == n) continue;
q.push(x);
previous[x] = node;
}
}
}
return vis[dest];
}
void solve(int start, int dest, vector< vector<int> >& g) {
while(findPaths(start, dest, g)) {
for(int x : g[dest]) {
int maxFlow = INF;
previous[dest] = x;
x = dest;
while(previous[x] != x) {
maxFlow = min(maxFlow, capacity[previous[x]][x] - flow[previous[x]][x]);
x = previous[x];
}
x = dest;
while(previous[x] != x) {
flow[previous[x]][x] += maxFlow;
flow[x][previous[x]] -= maxFlow;
x = previous[x];
}
solution += maxFlow;
}
}
}
int main() {
read();
/*Practic se cauta taietura minima
the max-flow min-cut theorem states that in a flow network, the maximum amount of flow
passing from the source to the sink is equal to the minimum capacity that,
when removed in a specific way from the network, causes the situation that
no flow can pass from the source to the sink.
*/
// Se taie muchii (si se adauga altele, inversele) pana cand nu mai poti accesa dest din sursa
// Complexitate: BFS O(M) => O(N * M^ 2), adica trebuie sa repet de N*M
//idee de demonstratie a de ce trebuie sa repet de atatea ori: dupa M repetari drumul scade cu un nod.
solve(1, n, g);
fout << solution << '\n';
return 0;
}