模板题。最小费用最大流,要求同时输出最大流以及最小费用,复杂度有点玄学,每增广一次,下一次SPFA的复杂度又会降低。所以这种题暂时只能这么处理:看出来有后效性的相互约束关系的就考虑用费用流解决。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int N=5004,M=50004,INF=0x3f3f3f3f;
int n,m,source,sink;
int head[N],etot=0,dis[N],pre[N];
bool inq[N];
struct EDGE {
int u,v,nxt,c,r;
}e[M<<1];
inline int read() {
int x=0;char c=getchar();
while (c<'0'||c>'9') c=getchar();
while (c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
return x;
}
inline void adde(int u,int v,int r,int c) {
e[etot].nxt=head[u],e[etot].u=u,e[etot].v=v,e[etot].r=r,e[etot].c=c,head[u]=etot++;
e[etot].nxt=head[v],e[etot].u=v,e[etot].v=u,e[etot].r=0,e[etot].c=-c,head[v]=etot++;
}
inline bool SPFA() {
queue<int > q;
memset(dis,INF,sizeof(dis));
memset(inq,false,sizeof(inq));
pre[source]=-1,dis[source]=0,inq[source]=true;
q.push(source);
while (!q.empty()) {
int p=q.front();
q.pop();
inq[p]=false;
for (int i=head[p];~i;i=e[i].nxt) {
int v=e[i].v;
if (e[i].r>0&&dis[v]>dis[p]+e[i].c) {
dis[v]=dis[p]+e[i].c;
pre[v]=i;
if (!inq[v]) q.push(v),inq[v]=true;
}
}
}
return dis[sink]^INF;
}
inline void MCMF() {
int maxflow=0,mincost=0;
while (SPFA()) {
int temp=INF;
for (int i=pre[sink];~i;i=pre[e[i].u]) temp=min(temp,e[i].r);
maxflow+=temp,mincost+=temp*dis[sink];
for (int i=pre[sink];~i;i=pre[e[i].u]) e[i].r-=temp,e[i^1].r+=temp;
}
printf("%d %d\n",maxflow,mincost);
}
int main() {
// freopen("P3381.in","r",stdin);
memset(head,-1,sizeof(head));
n=read(),m=read(),source=read(),sink=read();
for (register int i=0;i<m;++i) {
int u=read(),v=read(),r=read(),c=read();
adde(u,v,r,c);
}
MCMF();
return 0;
}