Pagini recente » Cod sursa (job #2924355) | Cod sursa (job #2060773) | Cod sursa (job #1814415) | Cod sursa (job #1842540) | Cod sursa (job #2897182)
#include <bits/stdc++.h>
using namespace std;
ifstream in("fmcm.in");
ofstream out("fmcm.out");
vector <int> v[351];
int cap[351][351],cost[351][351],n,dist[351],s,d,S,D;
bool incoada[351];
int daddy[351];
priority_queue <pair<int,int>> pq;
pair <int,int> dijkstra()
{
int i;
for(i=1; i<=n; i++)
dist[i]=1e9;
dist[s]=0;
pq.push({0,s});
int cst=0,flow=1e9;
while(!pq.empty())
{
int x=pq.top().second;
pq.pop();
for(auto it:v[x])
if(cap[x][it]&&dist[it]>dist[x]+cost[x][it])
{
dist[it]=dist[x]+cost[x][it];
daddy[it]=x;
pq.push({-dist[it],it});
}
}
if(dist[d]==1e9)
return {0,0};
for(i=d; i!=s; i=daddy[i])
flow=min(flow,cap[daddy[i]][i]);
for(i=d; i!=s; i=daddy[i])
{
cap[daddy[i]][i]-=flow;
cap[i][daddy[i]]+=flow;
}
cst=flow*(dist[d]-S+D);
return {flow,cst};
}
queue <int> q;
void bellman()
{
for(int i=1; i<=n; i++)
dist[i]=1e9;
dist[s]=0;
q.push(s);
incoada[s]=1;
while(!q.empty())
{
int x=q.front();
incoada[x]=0;
q.pop();
for(auto it:v[x])
if(cap[x][it]&&dist[it]>dist[x]+cost[x][it])
{
dist[it]=dist[x]+cost[x][it];
if(!incoada[it])
{
incoada[it]=1;
q.push(it);
}
}
}
}
int main()
{
int m,i,a,b,c,k;
in>>n>>m>>s>>d;
for(i=1; i<=m; i++)
{
in>>a>>b>>c>>k;
cost[a][b]=k;
cost[b][a]=-k;
cap[a][b]=c;
v[a].push_back(b);
v[b].push_back(a);
}
bellman();
S=dist[s];
D=dist[d];
for(i=1; i<=n; i++)
for(auto it:v[i])
cost[i][it]=cost[i][it]+dist[i]-dist[it];
pair <int,int> x;
int cost=0,flow=0;
do
{
x=dijkstra();
flow+=x.first;
cost+=x.second;
}
while(x!= make_pair(0,0));
out<<cost;
return 0;
}