组合数学 POJ 3252 Round Numbers

来源:互联网 发布:上瘾网络剧发布会视频 编辑:程序博客网 时间:2024/04/30 15:11

Description

The cows, as you know, have no fingers or thumbs and thus are unable to play Scissors, Paper, Stone’ (also known as ‘Rock, Paper, Scissors’, ‘Ro, Sham, Bo’, and a host of other names) in order to make arbitrary decisions such as who gets to be milked first. They can’t even flip a coin because it’s so hard to toss using hooves.

They have thus resorted to “round number” matching. The first cow picks an integer less than two billion. The second cow does the same. If the numbers are both “round numbers”, the first cow wins,
otherwise the second cow wins.

A positive integer N is said to be a “round number” if the binary representation of N has as many or more zeroes than it has ones. For example, the integer 9, when written in binary form, is 1001. 1001 has two zeroes and two ones; thus, 9 is a round number. The integer 26 is 11010 in binary; since it has two zeroes and three ones, it is not a round number.

Obviously, it takes cows a while to convert numbers to binary, so the winner takes a while to determine. Bessie wants to cheat and thinks she can do that if she knows how many “round numbers” are in a given range.

Help her by writing a program that tells how many round numbers appear in the inclusive range given by the input (1 ≤ Start < Finish ≤ 2,000,000,000).

Input

Line 1: Two space-separated integers, respectively Start and Finish.
Output

Line 1: A single integer that is the count of round numbers in the inclusive range Start..Finish
Sample Input

2 12
Sample Output

6

题目大意
输入两个数s、e,在[s,e]中有多少个数的二进制表示形式满足round number,即满足其二进制表示中 0 的数目大于或等于 1 的数目。

解题思路
首先,根据区间减法,将求解[s,e]区间的问题转化为求解[1,e+1]-[1,s]区间的问题;
对于一个十进制数x,先将其转化为二进制数,得其位数length,将满足条件的结果分为两部分来求:
1、位数小于length。满足条件的值有:对于每个小于length的位数 i ,至少需要填补 (i/2+1) 个 0,至多全为 0 。
2、位数与length相等。对于二进制序列由右至左进行检索(i 标记),若该位为0,标记0的个数zero +1;若该位为1,则先假设该位变为 0,那么无论右侧每位 1,0 取值如何,其值都小于x,即满足条件。满足条件的值有:在右侧的数位(即 i-1)中,至少需要填补(length+1)/2-(zero+1)个 0(zero+1加的是当前检索到的该位已由 1 变为 0 ),至多 i-1 个全为 0 。

代码实现

#include <iostream>#include<cstdio>using namespace std;int c[33][33]= {0};int binary[35];void c_bin(){    for(int i=0; i<33; i++)    {        for(int j=0; j<=i; j++)        {            if(!j||i==j)                c[i][j]=1;            else                c[i][j]=c[i-1][j]+c[i-1][j-1];        }    }}int cal(int n){    int sum,zero;    int length=0;    binary[0]=0;    sum=0,zero=0;    while(n)    {        binary[++length]=n%2;        n/=2;    }    for(int i=1; i<length-1; i++)    {        for(int j=i/2+1; j<=i; j++)        {            sum+=c[i][j];        }    }    for(int i=length-1; i>0; i--)    {        if(binary[i])        {            for(int j=(length+1)/2-(zero+1); j<=i-1; j++)                sum+=c[i-1][j];        }        else            zero++;    }    return sum;}int main(){    c_bin();    int s,e;    while(~scanf("%d%d",&s,&e))    {        printf("%d\n",cal(e+1)-cal(s));    }    return 0;}
0 0
原创粉丝点击