标签:
#include<stdio.h> #include<queue> #define MAXN 1003 #define MAXM 10002*4 #define INF 10000000 using namespace std; //起点编号必须最小,终点编号必须最大 bool vis[MAXN]; //spfa中记录是否在队列里边 struct edge{ edge *next,*op; //op是指向反向边 int t,c,v; //t下一个点编号,c容量,v权值 }ES[MAXM],*V[MAXN]; //ES边静态邻接表,V点的编号 int N,M,S,T,EC=-1; //S源点最小,T汇点最大,EC当前边数 int demond[MAXN],sp[MAXN],prev[MAXN]; //spSPFA中记录距离,prev记录上一个点路径 edge *path[MAXN]; //与prev同步记录,记录到上一条边 void addedge(int a,int b,int v,int c=INF){ edge e1={V[a],0,b,c,v},e2={V[b],0,a,0,-v}; ES[++EC]=e1;V[a]=&ES[EC]; ES[++EC]=e2;V[b]=&ES[EC]; V[a]->op=V[b];V[b]->op=V[a]; } void init(){ int i,a,b,c;; scanf("%d%d",&N,&M); for(int i=1;i<=N;i++){ scanf("%d",&demond[i]); } for(int i=1;i<=M;i++){ scanf("%d%d%d",&a,&b,&c); addedge(a,b+1,c); } S=0;T=N+2; for(int i=1;i<=N+1;i++){ c=demond[i]-demond[i-1]; if(c>=0)addedge(S,i,0,c); else addedge(i,T,0,-c); if(i>1)addedge(i,i-1,0); } } bool SPFA(){ int u,v; for(u=S;u<=T;u++){ sp[u]=INF; } queue<int>q; prev[S]=-1; q.push(S); sp[S]=0; vis[S]=1; while(!q.empty()){ u=q.front(); vis[u]=0; q.pop(); for(edge *k=V[u];k;k=k->next){ v=k->t; if(k->c>0&&sp[u]+k->v<sp[v]){ sp[v]=sp[u]+k->v; prev[v]=u; path[v]=k; if(vis[v]==0){ vis[v]=1; q.push(v); } } } } return sp[T]!=INF; } int argument(){ int i,cost=INF,flow=0; edge *e; for(i=T;prev[i]!=-1;i=prev[i]){ e=path[i]; if(e->c<cost)cost=e->c; } for(int i=T;prev[i]!=-1;i=prev[i]){ e=path[i]; e->c-=cost;e->op->c+=cost; flow+=e->v*cost; } return flow; } int maxcostflow(){ int Flow=0; while(SPFA()){ Flow+=argument(); } return Flow; } int main(){ init(); printf("%d\n",maxcostflow()); return 0; }
HYSBZ 1061 志愿者招募 【最小费用流】【差分】【最小费用流模板】
标签:
原文地址:http://www.cnblogs.com/tun117/p/5405790.html