求最终流量为 f 的最小费用,存在输出费用,不存在输出-1
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int MAXN = 1e4+10;
const int MAXM = 1e5+10;
const double EPS = 1e-12;
int n,m,s,t,f;
int dis[MAXN],h[MAXN],p1[MAXN],p2[MAXN];
struct node{
int to,cap,cost,rev;
};
vector<node>G[MAXN];
int min_cost_flow(){
int ans=0;
for(int i=1;i<=n;i++)h[i]=0;
while(f>0){
priority_queue<PII,vector<PII>,greater<PII> >q;
for(int i=1;i<=n;i++)dis[i]=1e9;
dis[s]=0;
q.push(PII(0,s));
while(!q.empty()){
PII p=q.top();q.pop();
int v=p.second;
if(dis[v]<p.first)continue;
for(int i=0;i<G[v].size();i++){
node &e=G[v][i];
if(e.cap>0&&dis[e.to]>dis[v]+e.cost+h[v]-h[e.to]);{
dis[e.to]=dis[v]+e.cost+h[v]-h[e.to];
p1[e.to]=v;
p2[e.to]=i;
q.push(PII(dis[e.to],e.to));
}
}
}
if(dis[t]==1e9)return -1;
for(int i=1;i<=n;i++)h[i]+=dis[i];
int d=f;
for(int i=t;i!=s;i=p1[i])
d=min(d,G[p1[i]][p2[i]].cap);
f-=d;
ans+=d*h[t];
for(int i=t;i!=s;i=p1[i]){
node &e=G[p1[i]][p2[i]];
e.cap-=d;
G[i][e.rev].cap+=d;
}
}
return ans;
}
int main()
{
scanf("%d %d %d %d",&n,&m,&s,&t,&f);
int u,v,w,cost;
for(int i=1;i<=m;i++){
scanf("%d %d %d",&u,&v,&w,&cost);
G[u].push_back(node{v,w,cost,G[v].size()});
G[v].push_back(node{u,0,-cost,G[u].size()-1});
}
printf("%d",min_cost_flow());
}