http://poj.org/problem?id=3252
看了discuss里面的解题报告才明白的,这个解题报告太强大了:http://poj.org/showmessage?message_id=158333不多讲已经很详细了,不明白多看几遍肯定会明白的。
注意这里的公式c(i,j) = c(i - 1,j -1) + c(i - 1,j);
c(n,0) + c(n,1) + c(n,2) + c(n,3) + ...... + c(n,n) = 2^n;
View Code
#include <cstdio> #include <cstring> #include <iostream> #define maxn 32 using namespace std;int pow2[maxn]; int c[maxn][maxn]; int b[maxn]; int s,e;void init() {int i,j;memset(pow2,0,sizeof(pow2));memset(c,0,sizeof(c));for (i = 0; i < maxn; ++i){pow2[i] = (1<<i);//打表2的i次方c[i][0] = c[i][i] = 1;}//求组合数for (i = 2; i < maxn; ++i){for (j = 1; j < i; ++j)c[i][j] = c[i - 1][j - 1] + c[i - 1][j];} } int solve(int x) {if (x <= 1) return 0;int n1,n0,i,j,len;int ans = 0;//求出x的二进制表示形式for (i = 0; i < maxn; ++i){if ((pow2[i]&x)!= 0) b[i] = 1;else b[i] = 0;}//找到开头为1的位置for (len = maxn - 1; b[len] == 0; --len){}//求长度维1,2,3,4,5....len的所有可能的和for (j = len; j >= 1; --j){if (j%2 == 1) ans += (pow2[j - 1] - c[j - 1][(j - 1)/2])/2;else ans += pow2[j - 1]/2;}//检查一下本身是不是满足条件n1 = n0 = 0;for (i = 0; i <= len; ++i){if (b[i]) n1++;else n0++;}if (n0 >= n1) ans++;//这就是第二部分的求解n0 = 0; n1 = 1;for (i = len - 1; i >= 0; --i){if (b[i]){//j + n0 + 1是当前可能的0的个数, i - j + n1是当前可能的1的个数for (j = i; j + n0 + 1 >= i - j + n1 && j >= 0; --j) ans += c[i][j];n1++;}else n0++;}return ans; } int main() {init();scanf("%d%d",&s,&e);printf("%d",solve(e) - solve(s - 1));return 0; }