最大流+SPFA结合体,小心即可。
#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
struct edge{
int to,cap,cost,rev;//终点,容量,费用,反向边
};
vector<edge>G[5010];
int dis[5010],prevv[5010],preve[5010],n,m,s,t,flow=0,cost=0;//最短路中前驱节点和对应的边
bool inque[5010];
void add(int from,int to,int cap,int cost)
{
G[from].push_back(edge{to,cap,cost,(int)G[to].size()});
G[to].push_back(edge{from,0,-cost,(int)G[from].size()-1});//注意反向边的加法!!-cost和cap=0!!
}
bool spfa(int s,int t)
{
memset(dis,0x3f, sizeof(dis));memset(inque,0,sizeof(inque));
queue<int>que;que.push(s);dis[s]=0;
while(!que.empty()){
int t=que.front();que.pop();inque[t]=false;
for(int i=0;i<G[t].size();i++){
edge e=G[t][i];
if(e.cap&&dis[e.to]>dis[t]+e.cost){
dis[e.to]=dis[t]+e.cost;
prevv[e.to]=t;preve[e.to]=i;
if(!inque[e.to]){
que.push(e.to);inque[e.to]=true;
}
}
}
}
if(dis[t]==0x3f3f3f3f)
return false;
int d=0x7f7f7f7f;
for(int v=t;v!=s;v=prevv[v])
d=min(d,G[prevv[v]][preve[v]].cap);//全最短路中的最小流量限制就是本次总的流量限制
flow+=d;cost+=d*dis[t];
for(int v=t;v!=s;v=prevv[v]){
edge&e=G[prevv[v]][preve[v]];//更新路径信息
e.cap-=d;
G[e.to][e.rev].cap+=d;
}
return true;
}
void mincostmaxflow(int s,int t)
{
while(spfa(s,t));
}
int main()
{
int i,j;
cin>>n>>m>>s>>t;
for(i=1;i<=m;i++){
int a,b,c,d;
scanf("%d%d%d%d",&a,&b,&c,&d);
add(a,b,c,d);
}
mincostmaxflow(s,t);
cout<<flow<<' '<<cost<<endl;
return 0;
}