好久没写网络流,今天放一套费用流模板在这。
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> PII; #define ls l,mid,rt<<1 #define rs mid+1,r,rt<<1|1 #define endl ' ' #define p4 puts("444") const int N = 5e3+10,M = 5e4+10; const double EPS = 1e-12; const ll mod = 1e9+7; int n,m,s,t,cnt; ll maxflow,cost; int head[N],cur[N],inq[N]; ll dis[N]; int book[N]; struct edge{ int to,next,cap; ll cost; }E[M<<1]; struct node{ inline void Add(int u,int v,int w,ll c){ E[cnt].to=v; E[cnt].cap=w; E[cnt].next=head[u]; E[cnt].cost=c; head[u]=cnt++; } inline bool Spfa(){ for(int i=1;i<=n;i++)cur[i]=head[i],dis[i]=1e18,inq[i]=0; queue<int>que; que.push(s); inq[s]=1; dis[s]=0; while(!que.empty()){ int u=que.front();que.pop(); inq[u]=0; for(int i=head[u];~i;i=E[i].next){ int v=E[i].to; if(E[i].cap&&dis[v]>dis[u]+E[i].cost){ dis[v]=dis[u]+E[i].cost; if(!inq[v]){ inq[v]=1; que.push(v); } } } } return dis[t]==1e18 ? 0 : 1; } inline int dfs(int u,int flow){ int rlow=0; if(u==t){ book[t]=1; maxflow+=flow; return flow; } int used=0; book[u]=1; for(int i=cur[u];~i;i=E[i].next){ cur[u]=i; int v=E[i].to; if((!book[v]||v==t)&&E[i].cap&&dis[v]==dis[u]+E[i].cost){ if(rlow=dfs(v,min(flow-used,E[i].cap))){ used+=rlow; cost+=rlow*E[i].cost; E[i].cap-=rlow; E[i^1].cap+=rlow; if(used==flow)break; } } } return used; } inline void Solve(){ while(Spfa()){ book[t]=1; while(book[t]){ memset(book,0,sizeof(book)); dfs(s,1e9); } } } }Dinic; int main() { maxflow=cost=cnt=0; scanf("%d %d %d %d",&n,&m,&s,&t); memset(head,-1,sizeof(head)); int u,v,w; ll c; for(int i=1;i<=m;i++){ scanf("%d %d %d %lld",&u,&v,&w,&c); Dinic.Add(u,v,w,c); Dinic.Add(v,u,0,-c); } Dinic.Solve(); printf("%lld %lld",maxflow,cost); }