1. 程式人生 > >luogo_3381【模板】最小費用最大流

luogo_3381【模板】最小費用最大流

int names push its als llc eof cap pty

#include<bits/stdc++.h>using namespace std;#define MAXM 500010#define MAXN 5010#define INF 100000000struct Edge{int from,to,cap,flow,cost;};int n,m,s,t,allflow,allcost;vector<Edge> edges;vector<int> G[MAXN];int d[MAXN],p[MAXN],a[MAXM];bool vis[MAXN];void Addedge(int from,int to,int cap,int cost){
edges.push_back((Edge){from,to,cap,0,cost}); edges.push_back((Edge){to,from,0,0,-cost}); int x=edges.size(); G[from].push_back(x-2); G[to].push_back(x-1);}bool BellmanFord(){ for(int i=1;i<=n;i++)d[i]=INF; memset(vis,0,sizeof(vis)); d[s]=0; vis[s]=1; p[s]=0; a[s]=INF; queue<int> Q; Q.push(s); while(!Q.empty()){
int u=Q.front(); Q.pop(); vis[u]=0; for(int i=0;i<G[u].size();i++){ Edge e=edges[G[u][i]]; if(e.cap>e.flow && d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; p[e.to]=G[u][i]; a[e.to]=min(a[u],e.cap-e.flow); if(!vis[e.to]){Q.push(e.to); vis[e.to]=1;} } } } if(d[t]==INF)return false;
allflow+=a[t]; allcost+=a[t]*d[t]; int u=t; while(u!=s){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; u=edges[p[u]].from; }}int main(){ scanf("%d%d%d%d",&n,&m,&s,&t); for(int i=1;i<=m;i++){ int u,v,w,c; scanf("%d%d%d%d",&u,&v,&w,&c); Addedge(u,v,w,c); } while(BellmanFord()); cout<<allflow<<‘ ‘<<allcost<<endl; return 0;}

luogo_3381【模板】最小費用最大流