• hdu 5106 组合数学+找规律


    http://acm.hdu.edu.cn/showproblem.php?pid=5106

    给定n和r,要求算出[0,r)之间所有n-onebit数的和,n-onebit数是所有数位中1的个数。

    对于一个n-bit数,可以根据与R最高不同位的位置分成几类。比如R=100100010,可以分成0xxxxxxxx,1000xxxxx,10010000x三类。x处可任取0或者1。x的个数为n,x中1的个数为k。和分两部分,高于n位的有C(n,k)乘以n位之前的数字,低于n位的部分有C(n-1,k-1)*(2^n−1) ( 对于k个1中的某一个1的位置,这个位置上有1在所有情况中占有了C(n-1,k-1)种情况,那么就相当于11...11(n个位置每个位置上都可能有1)*C(n-1,k-1),即C(n-1,k-1)*(2^n−1) )

    三次相乘一定要在第二次中间加一个%mod,血的教训!

    生成组合数的公式

    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <queue>
    #include <cstring>
    #include <algorithm>
    #define RD(x) scanf("%d",&x)
    #define RD2(x,y) scanf("%d%d",&x,&y)
    #define RD3(x,y,z) scanf("%d%d%d",&x,&y,&z)
    #define clr0(x) memset(x,0,sizeof(x))
    #define clr1(x) memset(x,-1,sizeof(x))
    using namespace std;
    typedef long long LL;
    const int maxn = 1005;
    const double eps = 1e-3;
    const int inf = 0x7fffffff;
    char p[maxn];
    const LL mod = 1000000007;
    LL c[maxn][maxn];
    LL q[maxn];
    void init()
    {
        for(int i = 0 ; i < maxn ; ++i){
            c[i][0] = 1;
        }
        for(int i = 1 ; i < maxn ; i++){
            for(int j = 1 ; j <= i ; ++j){
                c[i][j] = (c[i-1][j-1] + c[i-1][j])%mod;
            }
        }
    //    c[0][0] = 1;
    //    for(int i = 1;i < maxn;++i)
    //        for(int j = 0;j < i;++j){
    //            c[i][j] = (j == 0)?c[i-1][j] : c[i-1][j-1] + c[i-1][j];
    //            c[i][j] %= mod;
    //        }
        q[0] = 1;
        for(int i = 1;i < maxn;++i){
            q[i] = (q[i - 1]*2)%mod;
        }
    }
    int main()
    {
        init();
        int n,k;
        while(~scanf("%d%s",&n,p)){
            int m = strlen(p);
            int k = 0;
            LL ans = 0,tmp = 0;
            for(int st = 0;st < m;++st){
                if(p[st] == '1'){
                    ans += ((m-st-2>=0&&n-k-1>=0?c[m - st - 2][n - k - 1]:0) * (q[m - st - 1] - 1))%mod;
                    ans += (tmp * q[m - st]%mod * (m-st-1>=0&&n-k>=0?c[m - st - 1][n - k]:0))%mod;
                    ans %= mod;
                }
                tmp = (tmp*2 + p[st] - '0')%mod;
                k += p[st] - '0';
            }
            if(ans < 0) ans += mod;
            printf("%I64d
    ",ans);
        }
        return 0;
    }
    


  • 相关阅读:
    进程的实践与练习2
    士兵队列训练问题
    大数相加
    Ignatius and the Princess II
    Parentheses Balance (括号平衡)---栈
    简单计算器
    C++全排列函数next_permutation()和prev_permutation()
    黑白图像
    9*9乘法表
    输入5 个数按从小到大的顺序输出
  • 原文地址:https://www.cnblogs.com/zibaohun/p/4106643.html
Copyright © 2020-2023  润新知