5 5 8 -8 -10 12 -10 1 2 2 5 1 4 3 4 4 5
2
题目:http://acm.hdu.edu.cn/showproblem.php?pid=3061
PS:这题居然没能一下子想出图来,看来最小割的应用不够熟练阿~~~
分析:这题可以转化为求最小割,增加源和汇,把源与权为正的点连上界为该点权值的边,权为负的点与汇连上上界为该点权值相反数的边,然后如果攻占a必须先占b,则连上权值无穷的边a->b,所有正值之和减去最大流,即答案。。。
代码:
#include<cstdio> using namespace std; const int mm=1111111; const int mn=1111; const int oo=1000000000; int node,src,dest,edge; int ver[mm],flow[mm],next[mm]; int head[mn],work[mn],dis[mn],q[mn]; inline int min(int a,int b) { return a<b?a:b; } inline void prepare(int _node,int _src,int _dest) { node=_node,src=_src,dest=_dest; for(int i=0;i<node;++i)head[i]=-1; edge=0; } inline void addedge(int u,int v,int c) { ver[edge]=v,flow[edge]=c,next[edge]=head[u],head[u]=edge++; ver[edge]=u,flow[edge]=0,next[edge]=head[v],head[v]=edge++; } bool Dinic_bfs() { int i,u,v,l,r=0; for(i=0;i<node;++i)dis[i]=-1; dis[q[r++]=src]=0; for(l=0;l<r;++l) for(i=head[u=q[l]];i>=0;i=next[i]) if(flow[i]&&dis[v=ver[i]]<0) { dis[q[r++]=v]=dis[u]+1; if(v==dest)return 1; } return 0; } int Dinic_dfs(int u,int exp) { if(u==dest)return exp; for(int &i=work[u],v,tmp;i>=0;i=next[i]) if(flow[i]&&dis[v=ver[i]]==dis[u]+1&&(tmp=Dinic_dfs(v,min(exp,flow[i])))>0) { flow[i]-=tmp; flow[i^1]+=tmp; return tmp; } return 0; } int Dinic_flow() { int i,ret=0,delta; while(Dinic_bfs()) { for(i=0;i<node;++i)work[i]=head[i]; while(delta=Dinic_dfs(src,oo))ret+=delta; } return ret; } int main() { int u,v,c,m,n,sum; while(scanf("%d%d",&n,&m)!=-1) { prepare(n+2,0,n+1); for(u=1,sum=0;u<=n;++u) { scanf("%d",&c); if(c>0)addedge(src,u,c),sum+=c; if(c<0)addedge(u,dest,-c); } while(m--)scanf("%d%d",&u,&v),addedge(u,v,oo); printf("%d\n",sum-Dinic_flow()); } return 0; }