Pagini recente » Cod sursa (job #1792178) | Cod sursa (job #288414) | Solutii ONIS 2014, Runda 2 | Cod sursa (job #2470882) | Cod sursa (job #3039488)
#include <fstream>
#include <vector>
#include <queue>
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int const inf = 1e9 , N = 351;
int n , m , s , d , l , r , a , b;
int q[12501] , t[N] , viz[N] , dp[N] , dst[N] , inq[N];
int f[N][N] , w[N][N];
int w2[N][N];
vector<int> v[N];
int update(){
int flow = inf , cost = 0 , x = d;
while(t[x]){
flow = (flow < f[t[x]][x] ? 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;
}
void bellman(){
fill(dst + 1 , dst + 1 + n , inf);
fill(inq + 1 , inq + 1 + n , 0);
dst[s] = 0;
q[l = r = 1] = s;
inq[s] = 1;
while(l <= r){
int x = q[l++];
for(int y : v[x]){
if(f[x][y] > 0 && dst[y] > dst[x] + w[x][y]){
dst[y] = dst[x] + w[x][y];
if(!inq[y]){
q[++r] = y;
inq[y] = 1;
}
}
}
inq[x] = 0;
}
}
priority_queue<pii> h;
bool dijkstra(){
fill(viz + 1 , viz + 1 + n , 0);
fill(dp + 1 , dp + 1 + n , inf);
dp[s] = 0 , viz[s] = 1;
h.emplace(0 , s);
while(!h.empty()){
int x = h.top().se;
int wx = -h.top().fi;
h.pop();
for(int y : v[x]){
if(f[x][y] > 0 && !viz[y] && wx + w[x][y] + dst[x] - dst[y] < dp[y]){
dp[y] = wx + w[x][y] + dst[x] - dst[y];
viz[y] = 1;
t[y] = x;
h.emplace(-dp[y] , y);
}
}
}
return viz[d];
}
int fmcm(){
int cost(0);
while(dijkstra()){
cost += update();
}
return cost;
}
int main(){
fin >> n >> m >> s >> d;
for(int i = 1 ; i <= m ; ++ i){
fin >> a >> b >> f[a][b] >> w[a][b];
v[a].push_back(b);
v[b].push_back(a);
w[b][a] = -w[a][b];
}
bellman();
fout << fmcm() << '\n';
return 0;
}