题意:金典的最大获利问题,通信公司可以在n个地方建立信号站,每个信号站的建立要一定的费用,有m个要求,每个要求是如果两个地方都建立了信号站就会获利,求出公司的最大获利。
建图:获利边的选择要依赖点。源点跟边相连容量为边的获利,每个点跟汇点相连,容量为费用,每条边跟依赖的两个点相连,容量为无穷大,求出的最大流就是最小费用,,
#include<stdio.h> #include<string.h> const int N=55010; const int inf=0x3fffffff; int dis[N],gap[N],start,end,ans,head[N],num; struct edge { int st,ed,flow,next; }e[N*6]; void addedge(int x,int y,int w) { e[num].st=x;e[num].ed=y;e[num].flow=w;e[num].next=head[x];head[x]=num++; e[num].st=y;e[num].ed=x;e[num].flow=0;e[num].next=head[y];head[y]=num++; } int dfs(int u,int minflow) { if(u==end)return minflow; int i,v,f,min_dis=ans-1,flow=0; for(i=head[u];i!=-1;i=e[i].next) { v=e[i].ed; if(e[i].flow<=0)continue; if(dis[v]+1==dis[u]) { f=dfs(v,e[i].flow>minflow-flow?minflow-flow:e[i].flow); e[i].flow-=f; e[i^1].flow+=f; flow+=f; if(flow==minflow)break; if(dis[start]>=ans)return flow; } min_dis=min_dis>dis[v]?dis[v]:min_dis; } if(flow==0) { if(--gap[dis[u]]==0) dis[start]=ans; dis[u]=min_dis+1; gap[dis[u]]++; } return flow; } int isap() { int maxflow=0; memset(gap,0,sizeof(gap)); memset(dis,0,sizeof(dis)); gap[0]=ans; while(dis[start]<ans) maxflow+=dfs(start,inf); //printf("%d\n",maxflow); return maxflow; } int main() { int i,x,y,n,m,k,w; while(scanf("%d%d",&n,&m)!=-1) { memset(head,-1,sizeof(head)); num=0;start=0;end=n+m+1;ans=end+1;k=0; for(i=1;i<=n;i++) { scanf("%d",&x); addedge(i,end,x); } for(i=1;i<=m;i++) { scanf("%d%d%d",&x,&y,&w); addedge(n+i,x,inf); addedge(n+i,y,inf); addedge(start,n+i,w); k+=w; } printf("%d\n",k-isap()); } return 0; }