Pagini recente » Cod sursa (job #3004649) | Cod sursa (job #675377) | Cod sursa (job #700597) | Cod sursa (job #505371) | Cod sursa (job #1600458)
/*Edmonds-Karp algorithm using for detecting path a best first search algorithm
It takes the path which can be increased by a maximum flow */
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <queue>
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);
}
}
int findPaths(int start, int dest, vector< vector<int> >& g) {
priority_queue< pair<int, int> , vector< pair<int,int> >, greater< pair<int, int> > > pq;
vector<int> best(NMAX + 1, 0);
bitset<NMAX + 1> vis;
pq.push({INF, start});
previous[start] = start;
best[start] = INF;
while(pq.empty() == false) {
pair<int, int> edge = pq.top();
pq.pop();
vis[edge.second] = true;
for(int x : g[edge.second]) {
if(vis[x] == false) {
int maxFlow = min(best[edge.second], capacity[edge.second][x] - flow[edge.second][x]);
if(maxFlow > best[x]) {
best[x] = maxFlow;
pq.push({maxFlow, x});
previous[x] = edge.second;
}
}
}
}
return best[dest];
}
void solve(int start, int dest, vector< vector<int> >& g) {
int maxFlow;
while( (maxFlow = findPaths(start, dest, g) ) ) {
int x = dest;
while(previous[x] != x) {
flow[previous[x]][x] += maxFlow;
flow[x][previous[x]] -= maxFlow;
x = previous[x];
}
solution += maxFlow;
}
}
int main() {
read();
solve(1, n, g);
fout << solution << '\n';
return 0;
}