1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 #define MAXN 501 7 #define MAXM 50001 8 #define INF 2147483647 9 int S,T,n,m; 10 int en,u[MAXM],v[MAXM],first[MAXN],next[MAXM],cap[MAXM],cost[MAXM];//Next Array 11 bool inq[MAXN]; 12 int d[MAXN]/*spfa*/,p[MAXN]/*spfa*/,a[MAXN]/*可改进量*/; 13 queue<int>q; 14 void Init_MCMF(){memset(first,-1,sizeof(first));en=0;} 15 void AddEdge(const int &U,const int &V,const int &W,const int &C) 16 { 17 u[en]=U; v[en]=V; cap[en]=W; cost[en]=C; 18 next[en]=first[U]; first[U]=en++; 19 u[en]=V; v[en]=U; cap[en]=0; cost[en]=-C; 20 next[en]=first[V]; first[V]=en++; 21 } 22 bool Spfa(int &Flow,int &Cost) 23 { 24 memset(d,0x7f,sizeof(d)); 25 memset(inq,0,sizeof(inq)); 26 d[S]=0; inq[S]=1; p[S]=0; a[S]=INF; q.push(S); 27 while(!q.empty()) 28 { 29 int U=q.front(); q.pop(); inq[U]=0; 30 for(int i=first[U];i!=-1;i=next[i]) 31 if(cap[i] && d[v[i]]>d[U]+cost[i]) 32 { 33 d[v[i]]=d[U]+cost[i]; 34 p[v[i]]=i; 35 a[v[i]]=min(a[U],cap[i]); 36 if(!inq[v[i]]) {q.push(v[i]); inq[v[i]]=1;} 37 } 38 } 39 if(d[T]>2000000000) return 0; 40 Flow+=a[T]; Cost+=d[T]*a[T]; int U=T; 41 while(U!=S) 42 { 43 cap[p[U]]-=a[T]; cap[p[U]^1]+=a[T]; 44 U=u[p[U]]; 45 } 46 return 1; 47 } 48 int Mincost() 49 { 50 int Flow=0,Cost=0; 51 while(Spfa(Flow,Cost)); 52 return Cost; 53 }