UVALive4794 Sharing Chocolate

摘要

状压DP

链接

https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2795

题解

这题有个很好的特性,它要求每块地和加起来必须恰好等于整块的面积
所以 S e a c h   p a r t = S a l l ,也就是长乘宽等于每一块的面积之和,
设计状态 f [ x ] [ S ] 其中, x 是长和宽中较小的数, S 是一个二进制数,代表了一个集合,第 i 位为1表示第 i a i 被选中,因为 x y = A r e a ( S ) ,所以知道了 S x 就知道了 y
初始状态也就是 S 中只有一个元素,且 x A r e a ( S ) 的约数,这时的 f [ x ] [ S ] = t r u e
转移也有技巧
因为是从中间劈成两个,
先考虑横着劈开
可以先枚举 S 的真子集 s ,然后 s , S s 的面积如果都是 y 的倍数,就
f [ x ] [ S ] f [ m i n ( y , A r e a ( S ) / y ) ] [ s ]   a n d   f [ m i n ( y , A r e a ( S s ) / y ) ] [ S s ]
其中 a n d 是逻辑与
竖着劈同理
时间复杂度 O ( m i n ( x , y ) 3 n )
直接写会 T 掉,记忆化搜索 500 m s 即可过

代码

//状压DP
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cctype>
#define cl(x) memset(x,0,sizeof(x))
using namespace std;
int a[20], sum[(1<<15)+10], n, X, Y;
bool vis[110][(1<<15)+10], f[110][(1<<15)+10];
int read(int x=0)
{
    char c, f=1;
    for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+c-48;
    return x*f;
}
bool init()
{
    int i, j;
    cl(sum), cl(vis), cl(f);
    X=read(), Y=read();
    for(i=0;i<n;i++)a[i]=read();
    for(i=0;i<1<<n;i++)
        for(j=0;j<n;j++)if(i&(1<<j))sum[i]+=a[j];
    if(sum[(1<<n)-1]!=X*Y)return 0;
    return 1;
}
bool bitcount(int x)
{
    for(;(x&1)==0;x>>=1);
    return x==1;
}
int dp(int x, int S)        //记忆化搜索 
{
    int s, i, y=sum[S]/x;
    if(x>y)swap(x,y);
    if(vis[x][S])return f[x][S];
    vis[x][S]=1;
    if(bitcount(S))return f[x][S]=1;
    for(s=(S-1)&S;s and !f[x][S];s=(s-1)&S)
    {
        if(sum[s]%y==0 and sum[S^s]%y==0)f[x][S]=dp(y,s) and dp(y,S^s);
        if(!f[x][S] and sum[s]%x==0 and sum[S^s]%x==0)f[x][S]=dp(x,s) and dp(x,S^s);
    }
    return f[x][S];
}
//int gcd(int a, int b){return !b?a:gcd(b,a%b);}
//int dp()      //直接DP 
//{
//  int S, s, x, g;
//  for(S=1;S<1<<n;S<<=1)
//      for(x=1;x*x<=sum[S];x++)if(sum[S]%x==0)f[x][S]=1;
//  for(S=1;S<1<<n;S++)for(s=(S-1)&S;s;s=(s-1)&S)
//  {
//      g=gcd(sum[s],sum[S^s]);
//      for(x=1;x<=g and x*x<=sum[S] and x<=min(X,Y);x++)
//      {
//          if(g%x==0)f[x][S]|=f[min(x,sum[s]/x)][s] and f[min(x,sum[S^s]/x)][S^s];
//          if(g%(sum[S]/x)==0)f[x][S]|=f[min(sum[S]/x,sum[s]/(sum[S]/x))][s] and f[min(sum[S]/x,sum[S^s]/(sum[S]/x))][S^s];
//      }
//  }
//  return f[min(X,Y)][(1<<n)-1];
//}
int main()
{
    int c;
    for(c=1,n=read();n;n=read(),c++)
    {
        printf("Case %d: ",c);
        if(init())
        {
            if(dp(X,(1<<n)-1))printf("Yes\n");
            else printf("No\n");
        }
        else printf("No\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fsahfgsadhsakndas/article/details/81120441