Pagini recente » Cod sursa (job #1616520) | Cod sursa (job #987347) | Cod sursa (job #249636) | Cod sursa (job #1440344) | Cod sursa (job #1221891)
#include <fstream>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int N = 1 + 1e3, inf = 0x3f3f3f3f;
struct Nod{
int x, y, c;
Nod(int x, int y, int c) : x(x), y(y), c(c) {};
inline bool operator<(const Nod& N) const {
return c < N.c;
}
};
int cap[N][N], flux[N][N], T[N], n;
vector<int> graph[N];
bool use[N];
inline int getCap(int x, int y){
return cap[x][y] - flux[x][y];
}
inline void relax(int x, int y, int c){
flux[x][y] += c;
flux[y][x] -= c;
}
bool pfs(int x, int D){
memset(use, false, sizeof(use));
priority_queue<Nod> Q;
int t;
Q.push( Nod(0, x, 0) );
while (!Q.empty()){
x = Q.top().y;
t = Q.top().x;
Q.pop();
if (use[x])
continue;
use[x] = true;
T[x] = t;
for (int i : graph[x])
if (!use[i] && getCap(x, i) > 0)
Q.push( Nod(x, i, getCap(x, i)) );
}
return use[D];
}
bool bfs(int x, int D){
memset(use, false, sizeof(use));
queue<int> Q;
Q.push(x);
while (!Q.empty()){
x = Q.front();
Q.pop();
for (int i : graph[x])
if (!use[i] && getCap(x, i) > 0){
Q.push(i);
T[i] = x;
use[i] = true;
}
}
return use[D];
}
int maxFlow(int S, int D){
int flow = 0, F;
while ( bfs(S, D) )
for (int vecin : graph[D]){
F = getCap(vecin, D);
for (int i = vecin ; i != S ; i = T[i])
F = min(F, getCap(T[i], i));
if (!F) continue;
relax(vecin, D, F);
for (int i = vecin ; i != S ; i = T[i])
relax(T[i], i, F);
flow += F;
}
return flow;
}
int main(){
ifstream in("maxflow.in");
int m, x, y;
in >> n >> m;
while (m--){
in >> x >> y;
in >> cap[x][y];
graph[x].push_back(y);
graph[y].push_back(x);
}
in.close();
ofstream out("maxflow.out");
out << maxFlow(1, n) << '\n';
out.close();
return 0;
}