【BZOJ3107】二进制a+b,DP

Time:2016.08.24
Author:xiaoyimi
转载注明出处谢谢



传送门
思路:
今天的模拟题之一,现场脑补出的奥妙重重的DP思路
f[i][j][k][l][0/1] 表示DP到了第i位
此时X有j个1,Y有k个1,Z有l个1
i+1位是0还是1
f[i][j][k][l][0]>f[i+1][j+1][k+1][l+1][1]f[i+1][j+1][k][l+1][0]f[i+1][j][k+1][l+1][0]f[i+1][j][k][l][0]

f[i][j][k][l][1]>f[i+1][j+1][k+1][l+1][1]f[i+1][j][k+1][l][1]f[i+1][j+1][k][l][1]f[i+1][j][k][l][0]
答案就是 f[n][a1][b1][c1][0]
转移复杂度为 O(log42n) 常数略大
注意:要开一些奥妙重重的longlong
联动Shallwe的 O(log2n) 构造法
折越
代码:

#include
#include
#include
#include
#include
#define LL long long
using namespace std;
int T,a,b,c;
LL f[33][33][33][33][2];
int cal(int x)
{
    int sum=0;
    for (;x;x>>=1)
        sum+=x&1;
    return sum;
}
void work()
{
    scanf("%d%d%d",&a,&b,&c);
    memset(f,127,sizeof(f));
    int n=max((int)log2(a)+1,(int)log2(b)+1);
    n=max(n,(int)log2(c)+1);
    int la=cal(a),lb=cal(b),lc=cal(c);
    f[0][0][0][0][0]=0;
    for (int i=0;ifor (int j=0;j<=la;++j)
            for (int k=0;k<=lb;++k)
                for (int l=0;l<=lc;++l)
                {
                    LL tmp=f[i][j][k][l][0];
                    f[i+1][j+1][k+1][l+1][1]=min(f[i+1][j+1][k+1][l+1][1],tmp+(1<1));
                    f[i+1][j+1][k][l+1][0]=min(f[i+1][j+1][k][l+1][0],tmp+(1<1][j][k+1][l+1][0]=min(f[i+1][j][k+1][l+1][0],tmp+(1<1][j][k][l][0]=min(f[i+1][j][k][l][0],tmp);
                    tmp=f[i][j][k][l][1];
                    f[i+1][j+1][k+1][l+1][1]=min(f[i+1][j+1][k+1][l+1][1],tmp+(1<1));
                    f[i+1][j][k+1][l][1]=min(f[i+1][j][k+1][l][1],tmp+(1<1][j+1][k][l][1]=min(f[i+1][j+1][k][l][1],tmp+(1<1][j][k][l][0]=min(f[i+1][j][k][l][0],tmp);
                }
    printf("%lld\n",f[n][la][lb][lc][0]>=(1LL<<31)-1?-1:f[n][la][lb][lc][0]);
}
main(){work();}

你可能感兴趣的:(【BZOJ3107】二进制a+b,DP)