最小费用最大流

最小费用最大流

紫书P370 这个就是网络流调用Bellman算法

&代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
#define cle(a,val) memset(a,(val),sizeof(a))
#define SI(N) scanf("%d",&(N))
#define SII(N,M) scanf("%d %d",&(N),&(M))
#define SIII(N,M,K) scanf("%d %d %d",&(N),&(M),&(K))
#define rep(i,b) for(int i=0;i<(b);i++)
#define rez(i,a,b) for(int i=(a);i<=(b);i++)
#define red(i,a,b) for(int i=(a);i>=(b);i--)
const ll LINF = 0x3f3f3f3f3f3f3f3f;
#define PU(x) puts(#x);
#define PI(A) cout<<(A)<<endl;
#define DG(x) cout<<#x<<"="<<(x)<<endl;
#define DGG(x,y) cout<<#x<<"="<<(x)<<" "<<#y<<"="<<(y)<<endl;
#define DGGG(x,y,z) cout<<#x<<"="<<(x)<<" "<<#y<<"="<<(y)<<" "<<#z<<"="<<(z)<<endl;
#define PIar(a,n) rep(i,n)cout<<a[i]<<" ";cout<<endl;
#define PIarr(a,n,m) rep(aa,n){rep(bb, m)cout<<a[aa][bb]<<" ";cout<<endl;}
const double EPS = 1e-9 ; 
/*  ////////////////////////   C o d i n g  S p a c e   ////////////////////////  */
const int MAXN = 1000 + 5;
struct Edge{
	int from,to,cap,flow,cost;
};
int n,m;
vector<Edge> edges;
vector<int> G[MAXN];
int inq[MAXN];
int d[MAXN];
int p[MAXN];
int a[MAXN];
void Init(int n){
	for (int i=0;i<n;i++) 
		G[i].clear();
	edges.clear();
}
void AddEdge(int u,int v,int cap,int cost){
	edges.push_back((Edge){u,v,cap,0,cost});
	edges.push_back((Edge){v,u,0,0,-cost});
	int m=edges.size();
	G[u].push_back(m-2);
	G[v].push_back(m-1);
}
bool BellmanFord(int s,int t,int& flow,ll& cost){
	for (int i=0;i<n;i++)
		d[i]=INF;
	memset(inq,0,sizeof(inq));
	d[s]=0,inq[s]=1,a[s]=INF,p[s]=0;
	queue<int> Q;
	Q.push(s);
	while(!Q.empty()){
		int u=Q.front(); Q.pop();
		inq[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 (!inq[e.to]){
					Q.push(e.to);
					inq[e.to]=1;
				}
			}
		}
	}
	//the following is under the while()!!  not in the while()
	if (d[t]==INF) return false;
	flow+=a[t];
	cost+=(long long)d[t]*(long long)a[t];
	for (int u=t;u!=s;u=edges[p[u]].from){
		edges[p[u]].flow+=a[t];
		edges[p[u]^1].flow-=a[t];
	}	
	return true;
}
void MincostMaxflow(int s,int t,int& flow,long long& cost){
	flow=0,cost=0;
	while(BellmanFord(s,t,flow,cost));
}

void Solve()
{
    while(cin>>n>>m){
    	Init(n);
    	for (int i=0;i<m;i++){
    		int a1,a2,a3,a4;
    		cin>>a1>>a2>>a3>>a4;
    		a1--,a2--;
    		AddEdge(a1,a2,a3,a4);
    	}
    	int f; ll co;
    	MincostMaxflow(0,3,f,co);
    	DGG(f,co)
    }

}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("1.in", "r", stdin);
    freopen("1.out","w",stdout);
#endif
//iostream::sync_with_stdio(false);
//cin.tie(0), cout.tie(0);
    // int T;cin>>T;while(T--)
    Solve();
    return 0;
}
原文地址:https://www.cnblogs.com/s1124yy/p/6038970.html