Pagini recente » Cod sursa (job #1725295) | Cod sursa (job #3221238) | Cod sursa (job #2687962) | Cod sursa (job #2671594) | Cod sursa (job #2633374)
#include<bits/stdc++.h>
#define pb push_back
#define ft first
#define maxn 355
#define sd second
#define inf 0x3f3f3f3f
using namespace std;
vector<int>v[maxn];
vector<int>::iterator dest;
pair<int,int> c[maxn][maxn];
int cost[maxn],heap[maxn],poz[maxn],tt[maxn],n,m,d,s,flux,Cost,k;
void upheap(int x){
while(x!=1 && cost[heap[x]]<cost[heap[x/2]]){
swap(heap[x],heap[x/2]);
swap(poz[heap[x]],poz[heap[x/2]]);
x/=2;
}
}
void downheap(int x){
int son=1;
while(son){
son=0;
if(2*x<=k && cost[heap[x]]>cost[heap[2*x]])
son=2*x;
if(2*x+1<=k && cost[heap[x]]>cost[heap[2*x+1]] && cost[heap[2*x]]>cost[heap[2*x+1]])
son=2*x+1;
if(son){
swap(poz[heap[x]],poz[heap[son]]);
swap(heap[x],heap[son]);
}
x=son;
}
}
void solve(){
while(cost[d]!=inf){
memset(cost, inf, sizeof(cost));
cost[s]=0;
heap[1]=s;
k=poz[s]=1;
while(k){
int nod=heap[1];
poz[nod]=0;
swap(heap[1],heap[k]);
poz[heap[1]]=1;
k--; downheap(1);
if(nod==d)
continue;
for(dest=v[nod].begin(); dest!=v[nod].end(); dest++){
if(cost[nod]+c[nod][*dest].sd>=cost[*dest] || c[nod][*dest].ft==0)
continue;
cost[*dest]=cost[nod]+c[nod][*dest].sd;
tt[*dest]=nod;
if(poz[*dest]==0){
poz[*dest]=++k;
heap[k]=*dest;
upheap(k);
}else upheap(poz[*dest]);
}
}
if(cost[d]!=inf){
flux=inf;
if(cost[tt[d]]==inf || c[tt[d]][d].ft==0)
continue;
for(int wh=d; wh!=s; wh=tt[wh])
flux=min(flux, c[tt[wh]][wh].ft);
for(int wh=d; wh!=s; wh=tt[wh])
c[tt[wh]][wh].ft-=flux,
c[wh][tt[wh]].ft+=flux;
Cost+=flux*cost[d];
}
}
cout<<Cost;
}
int main(){
freopen("fmcm.in","r",stdin);
freopen("fmcm.out", "w", stdout);
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n>>m>>s>>d;
int x,y,z,w;
while(m--){
cin>>x>>y>>w>>z;
v[x].pb(y); v[y].pb(x);
c[x][y].ft=w; c[x][y].sd=z; c[y][x].sd=-z;
}
solve();
return 0;
}