标签:style blog io ar color os sp for on
一、非结构体版
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; 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]; 19 first[U]=en++; 20 u[en]=V; v[en]=U; cost[en]=-C; 21 next[en]=first[V]; 22 first[V]=en++; 23 } 24 bool Spfa(int &Flow,int &Cost) 25 { 26 memset(d,0x7f,sizeof(d)); 27 memset(inq,0,sizeof(inq)); 28 d[S]=0; inq[S]=1; p[S]=0; a[S]=INF; q.push(S); 29 while(!q.empty()) 30 { 31 int U=q.front(); q.pop(); inq[U]=0; 32 for(int i=first[U];i!=-1;i=next[i]) 33 if(cap[i] && d[v[i]]>d[U]+cost[i]) 34 { 35 d[v[i]]=d[U]+cost[i]; 36 p[v[i]]=i; 37 a[v[i]]=min(a[U],cap[i]); 38 if(!inq[v[i]]) {q.push(v[i]); inq[v[i]]=1;} 39 } 40 } 41 if(d[T]>2000000000) return 0; 42 Flow+=a[T]; Cost+=d[T]*a[T]; int U=T; 43 while(U!=S) 44 { 45 cap[p[U]]-=a[T]; cap[p[U]^1]+=a[T]; 46 U=u[p[U]]; 47 } 48 return 1; 49 } 50 int Mincost() 51 { 52 int Flow=0,Cost=0; 53 while(Spfa(Flow,Cost)); 54 return Cost; 55 }
二、结构体版
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 #define MAXN 5001 7 #define MAXM 100001 8 #define INF 2147483647 9 int S,T,n,m; 10 int en,first[MAXN]; 11 struct NextArray{int u,v,cap,cost,next;}NA[MAXM]; 12 bool inq[MAXN]; 13 int d[MAXN]/*spfa*/,p[MAXN]/*spfa*/,a[MAXN]/*可改进量*/; 14 queue<int>q; 15 void Init_MCMF(){en=0;memset(first,-1,sizeof(first));} 16 void AddEdge(const int &U,const int &V,const int &W,const int &C) 17 { 18 NA[en].u=U; NA[en].v=V; NA[en].cap=W; NA[en].cost=C; 19 NA[en].next=first[U]; first[U]=en++; 20 NA[en].u=V; NA[en].v=U; NA[en].cost=-C; 21 NA[en].next=first[V]; first[V]=en++; 22 } 23 bool Spfa(int &Flow,int &Cost) 24 { 25 memset(d,0x7f,sizeof(d)); 26 memset(inq,0,sizeof(inq)); 27 d[S]=0; inq[S]=1; p[S]=0; a[S]=INF; q.push(S); 28 while(!q.empty()) 29 { 30 int U=q.front(); q.pop(); inq[U]=0; 31 for(int i=first[U];i!=-1;i=NA[i].next) 32 if(NA[i].cap && d[NA[i].v]>d[U]+NA[i].cost) 33 { 34 d[NA[i].v]=d[U]+NA[i].cost; 35 p[NA[i].v]=i; 36 a[NA[i].v]=min(a[U],NA[i].cap); 37 if(!inq[NA[i].v]) {q.push(NA[i].v); inq[NA[i].v]=1;} 38 } 39 } 40 if(d[T]>2000000000) return 0; 41 Flow+=a[T]; Cost+=d[T]*a[T]; int U=T; 42 while(U!=S) 43 { 44 NA[p[U]].cap-=a[T]; NA[p[U]^1].cap+=a[T]; 45 U=NA[p[U]].u; 46 } 47 return 1; 48 } 49 int Mincost() 50 { 51 int Flow=0,Cost=0; 52 while(Spfa(Flow,Cost)); 53 return Cost; 54 }
标签:style blog io ar color os sp for on
原文地址:http://www.cnblogs.com/autsky-jadek/p/4149096.html