bzoj4873: [Shoi2017]寿司餐厅(网络流)

来源:互联网 发布:足不出户知天下 英语 编辑:程序博客网 时间:2024/04/28 02:00

题目传送门
神题啊。

解法:
最大权闭合子图。
不是很会用所以花了一整天的时间来想怎么构图。
然后之前做过最大获利这道题(bzoj1497)
那道题好像更水一点。
从那道题受到了一点点启发。
那么很显然要把每个区间都看成点啊。
那么按照最大权闭合子图st连正权点,负权连ed。
每个区间因为包含关系:
d[i][j]包含d[i+1][j],d[i][j-1]。
所以要向这两个区间连边。
然后对于每一个d[i][i]向这个寿司的编号连边,容量为编号。
然后对于每一个编号向ed连边,容量为m*编号的平方。
这样才符合题意。。
然后用正权和减去最大流就行了。

代码实现:

#include<cstdio>#include<cstring>#include<cstdlib>#include<iostream>#include<algorithm>#include<cmath>#include<queue>using namespace std;struct node {int x,y,c,next,other;}a[1110000];int len,last[110000];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 head,tail,list[110000],st,ed,h[110000];bool bt_h() {    memset(h,0,sizeof(h));h[st]=1;    head=1;tail=2;list[1]=st;    while(head!=tail) {        int x=list[head];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;            }        }    }    if(h[ed]==0)return false;    return true;}int findflow(int x,int f) {    if(x==ed)return f;    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&&s<f) {            t=findflow(y,min(a[k].c,f-s));s+=t;            a[k].c-=t;a[a[k].other].c+=t;        }    }    if(s==0)h[x]=0;    return s;}int s[110],d[110][110];const int inf=999999999;int b[1100];int main() {    int n,m;scanf("%d%d",&n,&m);    st=n*(n+1)/2+n+1;ed=st+1;int sum=0;    len=0;memset(last,0,sizeof(last));int cnt=n;    memset(b,0,sizeof(b));    for(int i=1;i<=n;i++){scanf("%d",&s[i]);        if(b[s[i]]==0)b[s[i]]=++cnt,ins(cnt,ed,s[i]*s[i]*m);        ins(i,ed,s[i]);ins(i,b[s[i]],inf);    }    for(int i=1;i<=n;i++)for(int j=i;j<=n;j++)d[i][j]=(i==j)?i:(++cnt);    for(int i=1;i<=n;i++)for(int j=i;j<=n;j++) {        int c;scanf("%d",&c);        if(c>0)sum+=c,ins(st,d[i][j],c);        else if(c<0)ins(d[i][j],ed,-c);        if(j!=i)ins(d[i][j],d[i+1][j],inf),ins(d[i][j],d[i][j-1],inf);    }    int ans=0;    while(bt_h()==true)ans+=findflow(st,inf);    printf("%d\n",sum-ans);    return 0;}
原创粉丝点击