Pagini recente » Cod sursa (job #69307) | Cod sursa (job #267461) | Cod sursa (job #3148369) | Cod sursa (job #101153) | Cod sursa (job #3039425)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int const inf = 1e9 , N = 351;
int n , m , s , d , x , y;
int t[N] , viz[N] , dp[N];
int f[N][N] , w[N][N];
int update(){
int flow = inf , cost = 0;
x = d;
while(t[x]){
flow = min(flow , f[t[x]][x]);
x = t[x];
}
if(!flow)
return 0;
x = d;
while(t[x]){
f[t[x]][x] -= flow;
f[x][t[x]] += flow;
cost += flow * w[t[x]][x];
x = t[x];
}
return cost;
}
bool bellman(){
fill(dp + 1 , dp + 1 + n , inf);
fill(t + 1 , t + 1 + n , 0);
queue<int> q;
q.push(s);
dp[s] = 0;
while(!q.empty()){
int x = q.front();
q.pop();
for(y = 1 ; y <= n ; ++ y){
if(f[x][y] > 0 && w[x][y] + dp[x] < dp[y]){
dp[y] = dp[x] + w[x][y];
t[y] = x;
q.push(y);
}
}
}
return t[d];
}
int fmcm(){
int cost(0);
while(bellman()){
cost += update();
}
return cost;
}
int main(){
fin >> n >> m >> s >> d;
for(int i = 1 ; i <= m ; ++ i){
fin >> x >> y >> f[x][y] >> w[x][y];
w[y][x] = -w[x][y];
}
fout << fmcm() << '\n';
return 0;
}