" This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved."
不知道理解的对不对,好像是不经过允许不准把题目贴出来的意思。所以就直接贴代码了。
思路:经过验算,可以得到,newB-newA-(b-a) 只能通过 *2 凑出来,所以遍历 *2 的个数,假设凑出来后使得 nowB-nowA==newB-newA 的乘 2 的个数是 m 个。如果nowA!=newA,那么现在又需要把n=newA-nowA凑出来,这时候,为了使得凑 n 用的步骤最少,可以构造,把 n 化成二进制,假设n化成二进制后有 k 位,比如说是 101,则可以看成 ((+1)*2)*2+1,但是可用的 *2 的个数不能超过 m 个,所以如果按照前面的构造的方法,如果 k>m 时,只能把从高到低的 k-m 个全部用+1 构造出来。比如说还是101,但是m=1,所以是 (+1)*10*2+1。最终在所有可选方案中取最小值。
(快过年了,记得要屯零食了!!!!!!,刷一题屯一种!!!)
通过系统测试的代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define INF 0x3f3f3f3f
class DoubleOrOneEasy{
public:
int query(int cou,int cha){
int ans=0;
for(int i=0;i<cou&&cha;i++){
if(cha%2){
ans++;
}
cha/=2;
}
//printf("%d %d %d\n",ans,cha,cou);
ans=ans+cha+cou;
return ans;
}
int minimalSteps(int a,int b,int newA,int newB){
int ans=INF;
if((long long int)(a-b)*(newA-newB)<=0&&(a-b!=0||newA-newB!=0)){
//printf("wo shi da hao ren1");
return -1;
}
else if(a>newA){
//printf("wo shi da hao ren2");
return -1;
}
else{
if(a>b){
swap(a,b);
swap(newA,newB);
}
int nowA=a,nowB=b;
int cou=0;
while(nowB<=newB){
if(nowB-nowA==newB-newA){
//printf("wo shi da hao ren3\n");
printf("%d %d\n",nowA,nowB);
ans=min(ans,query(cou,newA-nowA));
}
nowA*=2;
nowB*=2;
cou++;
//printf("wo shi da hao ren4\n");
}
if(ans==INF){
return -1;
}
else{
return ans;
}
}
}
};
int main(){
int a,b,newA,newB;
DoubleOrOneEasy temp;
while(scanf("%d%d%d%d",&a,&b,&newA,&newB)!=EOF){
printf("%d\n",temp.minimalSteps(a,b,newA,newB));
}
return 0;
}