Pagini recente » Cod sursa (job #1762420) | Cod sursa (job #2271660) | Cod sursa (job #2955359) | Cod sursa (job #2304150) | Cod sursa (job #2918780)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("fmcm.in");
ofstream fout("fmcm.out");
const int dim=409,inf=1e9;
vector<int>adj[dim];
int n,m,S,D;
int dist[dim];
int capacity[dim][dim],cost[dim][dim];
int cost_minim_flux;
int d[dim],real_dist[dim],parent[dim];
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>pq;
bool Dijkstra(){
for(int i=1;i<=n;i++){
d[i]=inf;
}
d[S]=real_dist[S]=0;
pq.push({d[S],S});
while(!pq.empty()){
int cost_curent=pq.top().first,x=pq.top().second;
pq.pop();
if(d[x]==cost_curent){
for(int y:adj[x]){
if(capacity[x][y]){
int new_d=d[x]+cost[x][y]+dist[x]-dist[y];
if(new_d<d[y]){
d[y]=new_d;
real_dist[y]=real_dist[x]+cost[x][y];
parent[y]=x;
pq.push({d[y],y});
}
}
}
}
}
if(d[D]==inf){
return false;
}
int minim=inf,cur=D;
while(cur!=S){
minim=min(minim,capacity[parent[cur]][cur]);
cur=parent[cur];
}
cost_minim_flux+=minim*real_dist[D];
cur=D;
while(cur!=S){
capacity[parent[cur]][cur]-=minim;
capacity[cur][parent[cur]]+=minim;
cur=parent[cur];
}
return true;
}
bool InQueue[dim];
void BellmanFord(){
for(int i=1;i<=n;i++){
dist[i]=inf;
}
queue<int>q;
dist[S]=0;
q.push(S);
InQueue[S]=true;
while(!q.empty()){
int x=q.front();
InQueue[x]=false;
q.pop();
for(int y:adj[x]){
if(capacity[x][y]){
if(dist[x]+cost[x][y]<dist[y]){
dist[y]=dist[x]+cost[x][y];
if(!InQueue[y]){
q.push(y);
InQueue[y]=true;
}
}
}
}
}
}
signed main(){
fin>>n>>m>>S>>D;
for(int i=1;i<=m;i++){
int x,y;
fin>>x>>y;
fin>>capacity[x][y]>>cost[x][y];
adj[x].push_back(y);
adj[y].push_back(x);
cost[y][x]=-cost[x][y];
}
BellmanFord();
while(Dijkstra()){
}
fout<<cost_minim_flux;
}