3144: [Hnoi2013]切糕

调了一下午居然是输入写成了v[i][j][k]

这题是最小割的经典模型,直接粘cgh的sol吧。。

这是一道很经典的网络流,HNOI2013 切糕。(个人感觉这题还是比T4难度低一点...
我们构造一个P*Q*(R+1)的点阵,用(i,j,k)表示一个点
那么(i,j,k) -> (i,j,k+1) 的流量为原图中(i,j,k)的不和谐值。
S向所有底层连无穷边,所有顶层向T连无穷边。
那么(i,j,k) -> (i,j,k+1)被割表示f(i,j)=k。。。
同时我们让(i,j,k) -> (i’,j’,k-D)连一条无穷边,就能保证相邻两个不超过D了。

我代码稍微有点不同。。st连i,j,1权为v[i][j][1]  i,j,k-1连i,j,k权为v[i][j][k]

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
const int inf=(1<<30);

struct node
{
    int x,y,c,next,other;
}a[2100000];int len,last[2100000];
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 st,ed;
int h[2100000],list[2100000];
bool bt_h()
{
    memset(h,0,sizeof(h));h[st]=1;
    int head=1,tail=2;list[1]=st;
    while(head!=tail)
    {
        int x=list[head];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(a[k].c>0&&h[y]==0)
            {
                h[y]=h[x]+1;
                list[tail]=y;
                tail++;
            }
        }
        head++;
    }
    if(h[ed]==0)return false;
    return true;
}
int findflow(int x,int f)
{
    if(x==ed)return f;
    int s=0;
    for(int k=last[x];k;k=a[k].next)
    {
        int y=a[k].y;
        if(a[k].c>0&&h[y]==h[x]+1&&s<f)
        {
            int 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;
}

//--------------findflow---------------

const int dx[4]={1,0,-1,0};
const int dy[4]={0,-1,0,1};
int P,Q,R,D;
int v[110][110][110];
int point(int x,int y,int z){return P*Q*(z-1)+P*(y-1)+x;}
void composition()
{
    st=P*Q*R+1,ed=P*Q*R+2;
    for(int i=1;i<=P;i++)
        for(int j=1;j<=Q;j++)
        {
            ins(st,point(i,j,1),v[i][j][1]);
            ins(point(i,j,R),ed,inf);
            for(int k=2;k<=R;k++)
                ins(point(i,j,k-1),point(i,j,k),v[i][j][k]);
        }
    for(int i=1;i<=P;i++)
        for(int j=1;j<=Q;j++)
            for(int u=0;u<=3;u++)
            {
                int ti=dx[u]+i,tj=dy[u]+j; 
                if(ti>0&&ti<=P&&tj>0&&tj<=Q)
                {
                    for(int k=D+1;k<=R;k++)
                        ins(point(i,j,k),point(ti,tj,k-D),inf);
                }
            }
}

int main()
{
    freopen("d.in","r",stdin);
    freopen("d.out","w",stdout);
    scanf("%d%d%d%d",&P,&Q,&R,&D);
    composition();    
    for(int k=1;k<=R;k++)
        for(int i=1;i<=P;i++)
            for(int j=1;j<=Q;j++)
                scanf("%d",&v[i][j][k]);
    composition();    
    int ans=0;
    while(bt_h()==true)
    {
        ans+=findflow(st,inf);
    }
    printf("%d\n",ans);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/AKCqhzdy/p/8921276.html