bzoj1497: [NOI2006]最大获利(最大权闭合子图)

1497: [NOI2006]最大获利

题目:传送门

题解:

  %%%关于最大权闭合子图很好的入门题


  简单说一下什么叫最大权闭合子图吧...最简单的解释就是正权边连源点,负权边连汇点(注意把边权改为正数)然后跑网络流,用正权和-最大流就是答案。

  从这道题我们其实就可以很好的意会:

  st向可以赚钱的点(正权)连一条流量为收益的边,负权点(花钱的)向ed连一条流量为成本的边。

  跑网络流...答案=总收益-成本

  %%%hanks_o大佬

  就像波老师说的:

  如果有一条路径流过的流量等于花费, 说明 利益>=花费,那这条路径肯定要选。 

  这样的话,总利益-最大流一定包括了这个利益。

  如果有一条路径流过的流量等于利益,说明 利益<=花费 ,那傻子才去选qwq 

  这样的话,总利益-最大流一定把这种情况去除了。

代码水的一匹:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#define qread(x)x=read();
using namespace std;
inline int read()
{
    int f=1,x=0;char ch;
    while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return f*x;
}
struct node
{
    int x,y,c,next,other;
}a[2110000];int len,last[1110000];
int st,ed,n,m,head,tail;
void ins(int x,int y,int c)
{
    int k1,k2;
    len++;k1=len;
    a[len].x=x;a[len].y=y;a[len].c=c;
    a[len].next=last[x];last[x]=len;
    
    len++;k2=len;
    a[len].x=y;a[len].y=x;a[len].c=0;
    a[len].next=last[y];last[y]=len;
    
    a[k1].other=k2;
    a[k2].other=k1;
}
int list[110000],h[110000];
bool bfs()
{
    memset(h,0,sizeof(h));h[st]=1;
    list[1]=st;head=1;tail=2;
    while(head!=tail)
    {
        int x=list[head];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(h[y]==0 && a[k].c>0)
            {
                h[y]=h[x]+1;
                list[tail++]=y;
            }
        }
        head++;
    }
    if(h[ed]>0)return true;
    return false;
}
int findflow(int x,int flow)
{
    if(x==ed)return flow;
    int s=0,t;
    for(int k=last[x];k;k=a[k].next)
    {
        int y=a[k].y;
        if(h[y]==h[x]+1 && a[k].c>0 && flow>s)
        {
            t=findflow(y,min(a[k].c,flow-s));
            s+=t;
            a[k].c-=t;a[a[k].other].c+=t;
        }
    }
    if(s==0)h[x]=0;
    return s;
}
int d[51000];
int sum;
int main()
{
    len=0;memset(last,0,sizeof(last));
    qread(n);qread(m);
    st=n+m+1;ed=n+m+2;sum=0;
    for(int i=1;i<=n;i++)
    {
        qread(d[i]);
        ins(i,ed,d[i]);
    }
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        qread(x);qread(y);qread(c);
        sum+=c;
        ins(i+n,x,999999999);
        ins(i+n,y,999999999);
        ins(st,i+n,c);
    }
    int ans=0;
    while(bfs())ans+=findflow(st,999999999);
    printf("%d
",sum-ans);
    return 0;
}
原文地址:https://www.cnblogs.com/CHerish_OI/p/8010576.html