洛谷P3381 (最小费用最大流模板)
作者:互联网
记得把数组开大一点,不然就RE了。。。
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define int long long 4 const int N=5e5; 5 const int M=5e5; 6 const int INF=0x3f3f3f3f; 7 8 int n,m,s,t,ans,d[N],maxflow; 9 int tot=1,adj[N],nex[M],to[M],cap[M],cost[M]; 10 bool walk[N],vis[N]; 11 12 void add(int u,int v,int w,int c){ 13 nex[++tot]=adj[u]; 14 adj[u]=tot; 15 to[tot]=v; 16 cap[tot]=w; 17 cost[tot]=c; 18 } 19 20 bool SPFA(){ 21 queue<int> q; 22 for(int i=1;i<=n;i++) 23 vis[i]=false,walk[i]=false,d[i]=INF; 24 q.push(s),d[s]=0,vis[s]=true; 25 while(!q.empty()){ 26 int u=q.front();q.pop(); 27 vis[u]=false; 28 for(int i=adj[u];i;i=nex[i]){ 29 int v=to[i]; 30 if(cap[i]>0&&d[u]+cost[i]<d[v]){ 31 d[v]=d[u]+cost[i]; 32 if(!vis[v]){ 33 vis[v]=true; 34 q.push(v); 35 } 36 } 37 } 38 } 39 return d[t]<INF; 40 } 41 42 int dinic(int u,int fw){ 43 if(u==t){ 44 ans+=fw*d[t]; 45 return fw; 46 } 47 walk[u]=true; 48 int rest=fw; 49 for(int i=adj[u];i&&rest;i=nex[i]){ 50 int v=to[i]; 51 if(!walk[v]&&cap[i]>0&&d[u]+cost[i]==d[v]){ 52 int k=dinic(v,min(cap[i],rest)); 53 if(k){ 54 cap[i]-=k;cap[i^1]+=k; 55 rest-=k; 56 } 57 } 58 } 59 return fw-rest; 60 } 61 62 void solve(){ 63 maxflow=ans=0; 64 while(SPFA()) maxflow+=dinic(s,INF); 65 } 66 67 signed main(){ 68 cin>>n>>m>>s>>t; 69 for(int i=1;i<=m;i++){ 70 int u,v,w,c; 71 cin>>u>>v>>w>>c; 72 add(u,v,w,c); 73 add(v,u,0,-c); 74 } 75 solve(); 76 cout<<maxflow<<" "<<ans; 77 return 0; 78 }
标签:洛谷,int,cap,tot,cost,rest,P3381,const,模板 来源: https://www.cnblogs.com/yhxnoerror/p/16099177.html