Pagini recente » Cod sursa (job #2061073) | Cod sursa (job #1804237) | Cod sursa (job #1875994) | Cod sursa (job #2184159) | Cod sursa (job #2586538)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
typedef long long lint;
const int INF = 0x3f3f3f3f;
struct nod{
int a, v = INF;
bool operator<(const nod &rhs)const{
if(v != rhs.v){
return v > rhs.v;
}else{
return a < rhs.a;
}
}
};
const int N = 410;
int n, m, s, d;
int cap[N][N];
int rcst[N][N];
vector<int> gra[N];
void read(){
fin >> n >> m >> s >> d;
for(int i = 0; i < m; ++i){
int a, b;
fin >> a >> b;
fin >> cap[a][b] >> rcst[a][b];
rcst[b][a] = -rcst[a][b];
gra[a].push_back(b);
gra[b].push_back(a);
}
}
int dist[N];
int rdist[N];
void nuke(){
for(int i = 1; i <= n; ++i){
dist[i] = INF;
}
dist[s] = 0;
}
void bellman(){
static queue<int> qu;
static bool vi[N];
nuke();
qu.push(s);
vi[s] = true;
while(!qu.empty()){
int a = qu.front();
qu.pop();
vi[a] = false;
for(auto b : gra[a]){
int v = dist[a]+rcst[a][b];
if(v < dist[b] && cap[a][b] != 0){
dist[b] = v;
if(!vi[b]){
qu.push(b);
vi[b] = true;
}
}
}
}
}
int cst[N][N];
void postbellman(){
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
cst[i][j] = dist[i] - dist[j] + rcst[i][j];
}
}
}
priority_queue<nod> pq;
int dad[N];
bool dijkstra(){
nuke();
pq.push({s, 0});
rdist[s] = 0;
while(!pq.empty()){
nod nd = pq.top();
int a = nd.a;
pq.pop();
if(nd.v == dist[a]){
for(auto b : gra[a]){
int v = dist[a] + cst[a][b];
if(v < dist[b] && cap[a][b] > 0){
dad[b] = a;
dist[b] = v;
rdist[b] = rdist[a]+rcst[a][b];
pq.push({b, dist[b]});
}
}
}
}
return dist[d] != INF;
}
lint updateflow(){
int fmin = INF;
for(int x = d; x != s; x = dad[x]){
fmin = min(fmin, cap[dad[x]][x]);
}
if(fmin != 0){
for(int x = d; x != s; x = dad[x]){
cap[dad[x]][x] -= fmin;
cap[x][dad[x]] += fmin;
}
return fmin*rdist[d];
}
return 0;
}
lint ans = 0;
void maxflow(){
while(dijkstra()){
ans += updateflow();
}
}
void solve(){
bellman();
postbellman();
maxflow();
}
int main(){
// ios_base::sync_with_stdio(false);
read();
solve();
fout << ans;
return 0;
}