2013南京邀请赛C题/njustOJ 1739 - Count The Carries


Count The Carries

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 0    Accepted Submission(s): 0


Problem Description
  
  
One day, Implus gets interested in binary addition and binary carry. He will transfer all decimal digits to binary digits to make the addition. Not as clever as Gauss, to make the addition from a to b, he will add them one by one from a to b in order. For example, from 1 to 3 (decimal digit), he will firstly calculate 01 (1)+10 (2), get 11,then calculate 11+11 (3),lastly 110 (binary digit), we can find that in the total process, only 2 binary carries happen. He wants to find out that quickly. Given a and b in decimal, we transfer into binary digits and use Implus's addition algorithm, how many carries are there?
 

Input
  
  
Two integers a, b(0<=a<=b<1000000000), about 100000 cases, end with EOF.
 

Output
  
  
One answer per line.
 

Sample Input
  
  
1 2 1 3 1 4 1 6
 

Sample Output
  
  
0 2 3 6

题解转自 kk303

.常规的把握是求0~a-1的..与0~b的.... 再用后者减去前者得到答案...

      通过观察..问题可以转化为..求a加到b的不进位二进制数..然后再通过至右向左的进位统计二进制的进位次数...再转化..就是求从a~b这些数...每一位有多少个1.....

      如从0~3...表示成不进位的二进制数位22...再对22进位成合法的二进制数...22 -> 30 , 30 -> 110...一共进位两次.....

      那么如何统计每一位上1的个数呢?通过几次演算..不难发现..从0+1+2+....x...当x为2^p-1时...该二进制数为2^p 2^p 2^p...

      如0加到3为22.....0加到7为444...0加到15为8888.....

      那么如何求不是2^p-1的数呢?

      比如说10....比10小的最大2^p-1数是7...所以可以先得到0加到7的情况...444...还剩下了8,9,10没有加..而8,9,10若是去掉最高位的1..不就是0加到2的情况...

      所以0加到10的不进位二进制数为444(0加到7)+300(8,9,10的高位)+011(0加到2)=755...

      但注意...结果并不是数出0加到a-1的进位数s1...数出0到b的进位数s2...s2-s1....而是算出0加到a-1和0到b的不进位二进制数..用后者减去前者之后..再进行进位统计...      


#include<fstream>
#include<iostream>
#include<cstdio>
#include<cstring>
#define FOR(i,a,b) for(int i=a;i<=b;++i)
#define clr(f,z) memset(f,z,sizeof(f))
#define LL long long
#define ll(x) (1<<x)
using namespace std;
const int mm=66;
LL f1[mm],f2[mm];
void get(LL*f,LL x)
{
 clr(f,0);
 int p=30;
 while(x>0)///统0-x的和
 {
  while(x<ll(p))--p;
  FOR(i,0,p-1)f[i]+=ll(p-1);
  f[p]+=x+1-ll(p);
  x-=ll(p);
 }
}
int main()
{ LL a,b;
  while(cin>>a>>b)
  {clr(f1,0);clr(f2,0);
   get(f1,a-1);get(f2,b);
   FOR(i,0,mm-1)
   f2[i]-=f1[i];
   LL ans=0;
   FOR(i,0,mm-1)
   {
    ans+=f2[i]/2;
    f2[i+1]+=f2[i]/2;
   }
   cout<<ans<<endl;
  }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值