1. 程式人生 > >BZOJ 3107 [cqoi2013]二進位制a+b (DP)

BZOJ 3107 [cqoi2013]二進位制a+b (DP)

3107: [cqoi2013]二進位制a+b

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 995  Solved: 444
[Submit][Status][Discuss]

Description

輸入三個整數a, b, c,把它們寫成無前導0的二進位制整數。比如a=7, b=6, c=9,寫成二進位制為a=111, b=110, c=1001。接下來以位數最多的為基準,其他整數在前面新增前導0,使得a, b, c擁有相同的位數。比如在剛才的例子中,新增完前導0後為a=0111, b=0110, c=1001。最後,把a, b, c的各位進行重排,得到a’, b’, c’,使得a’+b’=c’。比如在剛才的例子中,可以這樣重排:a’=0111, b’=0011, c’=1010。 你的任務是讓c’最小。如果無解,輸出-1。  

Input

輸入僅一行,包含三個整數a, b, c。  

Output

  輸出僅一行,為c’的最小值。

Sample Input

7 6 9

Sample Output

10

HINT

 

a,b,c<=2^30

題解:

參考程式碼:dp[i][j][k][l][m]表示:第I位,第1,2,3個數分別用了幾個一,m表示是否有進位:

分類討論:

  對於m=0的情況: 

   dp[i+1][j+1][k+1][l+1][1]=min(dp[i+1][j+1][k+1][l+1][1],tmp+(1<<i+1));
    dp[i+1][j+1][k][l+1][0]=min(dp[i+1][j+1][k][l+1][0],tmp+(1<<i));
    dp[i+1][j][k+1][l+1][0]=min(dp[i+1][j][k+1][l+1][0],tmp+(1<<i));
    dp[i+1][j][k][l][0]=min(dp[i+1][j][k][l][0],tmp);
 對於m=1的情況:
    dp[i+1][j+1][k+1][l+1][1]=min(dp[i+1][j+1][k+1][l+1][1],tmp+(1<<i+1));
    dp[i+1][j][k+1][l][1]=min(dp[i+1][j][k+1][l][1],tmp+(1<<i));
    dp[i+1][j+1][k][l][1]=min(dp[i+1][j+1][k][l][1],tmp+(1<<i));
    dp[i+1][j][k][l][0]=min(dp[i+1][j][k][l][0],tmp);	
#include<bits/stdc++.h>
using namespace std;
#define clr(a,b) memset(a,b,sizeof(a))
typedef long long ll;
const ll inf=0x3f3f3f3f3f3f3f3fll;
ll a,b,c;
ll la,lb,lc,len;
ll dp[62][40][40][40][2];
void getlen(){len=max(log2(a)+1,max(log2(b)+1,log2(c)+1));}
ll getnum(ll x)
{
	ll sum=0;
	for(int i=0;i<62;++i) {if( x & (1ll<<i) ) sum++; }
	return sum;
}
void work()
{
	dp[0][0][0][0][0]=0;
	for(ll i=0;i<len;++i)
	{
		for(ll j=0;j<=la;++j)
		{
			for(ll k=0;k<=lb;++k)
			{
				for(ll l=0;l<=lc;++l)
				{
					 long long tmp=dp[i][j][k][l][0];//列舉最後一位不進位的情況
                    dp[i+1][j+1][k+1][l+1][1]=min(dp[i+1][j+1][k+1][l+1][1],tmp+(1<<i+1));
                    dp[i+1][j+1][k][l+1][0]=min(dp[i+1][j+1][k][l+1][0],tmp+(1<<i));
                    dp[i+1][j][k+1][l+1][0]=min(dp[i+1][j][k+1][l+1][0],tmp+(1<<i));
                    dp[i+1][j][k][l][0]=min(dp[i+1][j][k][l][0],tmp);
                    tmp=dp[i][j][k][l][1];//列舉最後一位進位的情況
                    dp[i+1][j+1][k+1][l+1][1]=min(dp[i+1][j+1][k+1][l+1][1],tmp+(1<<i+1));
                    dp[i+1][j][k+1][l][1]=min(dp[i+1][j][k+1][l][1],tmp+(1<<i));
                    dp[i+1][j+1][k][l][1]=min(dp[i+1][j+1][k][l][1],tmp+(1<<i));
                    dp[i+1][j][k][l][0]=min(dp[i+1][j][k][l][0],tmp);	
				}	
			}	
		}	
	} 
	//cout<<len<<" "<<la<<" "<<lb<<" "<<lc<<endl;
	if(dp[len][la][lb][lc][0]>=inf) printf("-1\n");
	else printf("%d\n",dp[len][la][lb][lc][0]);
}

int main()
{
	scanf("%lld%lld%lld",&a,&b,&c);
	getlen(); memset(dp,inf,sizeof dp);
	la=getnum(a);lb=getnum(b);lc=getnum(c);
	work();
	return 0;
}