Pagini recente » Cod sursa (job #1904381) | Cod sursa (job #2162815) | Cod sursa (job #3243519) | Cod sursa (job #2313493) | Cod sursa (job #1543069)
#include<cstdio>
#include<vector>
#include<queue>
#define inf 2000000000
using namespace std;
vector<int> g[355];
int flow[355][355],capacity[355][355],cost[355][355],n,s,d,old[355],real[355],best[355],in_queue[355],dad[400];
queue<int> q;
struct node{
int index,cost;
const bool operator < (const node&b) const{
return this->cost>b.cost;
}
};
node temp;
priority_queue<node> h;
int minim(int a,int b){
if(a<b)
return a;
return b;
}
void bellman_ford(){
int i,dim,node;
for(i=1;i<=n;i++)
old[i]=inf;
old[s]=0;
q.push(s);
in_queue[s]=1;
while(!q.empty()){
node=q.front();
q.pop();
in_queue[node]=0;
dim=g[node].size();
for(i=0;i<dim;i++){
if(capacity[node][g[node][i]]==flow[node][g[node][i]])
continue;
if(old[g[node][i]]>old[node]+cost[node][g[node][i]]){
old[g[node][i]]=old[node]+cost[node][g[node][i]];
if(in_queue[g[node][i]]==0){
in_queue[g[node][i]]=1;
q.push(g[node][i]);
}
}
}
}
}
int dijkstra(){
int i,dim,node,current,distance;
for(i=1;i<=n;i++)
best[i]=inf;
best[s]=real[s]=0;
temp.index=s;
temp.cost=0;
h.push(temp);
while(!h.empty()){
node=h.top().index;
current=h.top().cost;
dim=g[node].size();
h.pop();
if(best[node]!=current)
continue;
for(i=0;i<dim;i++){
if(capacity[node][g[node][i]]==flow[node][g[node][i]])
continue;
distance=current+cost[node][g[node][i]]+old[node]-old[g[node][i]];
if(distance<best[g[node][i]]){
best[g[node][i]]=distance;
real[g[node][i]]=real[node]+cost[node][g[node][i]];
dad[g[node][i]]=node;
temp.index=g[node][i];
temp.cost=best[g[node][i]];
h.push(temp);
}
}
}
if(best[d]==inf)
return 0;
for(i=1;i<=n;i++)
old[i]=real[i];
return 1;
}
int main(){
freopen("fmcm.in","r",stdin);
freopen("fmcm.out","w",stdout);
int m,x,y,a,b,i,node,add,maxflow=0,mincost=0;
scanf("%d%d%d%d",&n,&m,&s,&d);
for(i=1;i<=m;i++){
scanf("%d%d%d%d",&x,&y,&a,&b);
g[x].push_back(y);
g[y].push_back(x);
cost[x][y]+=b;
cost[y][x]-=b;
capacity[x][y]+=a;
}
bellman_ford();
a=0;
while(dijkstra()==1){
a++;
add=inf;
node=d;
while(node!=s){
add=minim(add,capacity[dad[node]][node]-flow[dad[node]][node]);
node=dad[node];
}
node=d;
while(node!=s){
flow[dad[node]][node]+=add;
flow[node][dad[node]]-=add;
node=dad[node];
}
maxflow+=add;
mincost+=add*real[d];
}
printf("%d",mincost);
return 0;
}