hdu 5106 同余定理+组合数学+快速幂

来源:互联网 发布:魔兽中机械宠物矩阵 编辑:程序博客网 时间:2024/05/21 19:29

首先要取模,就要用到同余模定理,具体不细讲,只是在中间过程取模,防止溢出

在统计时考虑,逐位进行,因为不考虑数本身,所以每当遇到1时,考虑后面还需要n个1,还剩多少m位,所以就有c(m,n)个数,因为这些数的前缀相同,所以最终结果可以通过前缀*个数获得这部分的和,然后考虑每个位上是1的情况是c(m-1,n-1),也就是当前位固定为1,其他位任意选的情况数,那么他们的和就是(2^(n+1)-1)*c(m-1,n-1),快速幂只是在求幂的时候的优化,也可以提前打好表,效率更高

ac代码如下:

#include <iostream>#include <cstring>#include <algorithm>#include <cstdio>#define MOD 1000000007#define MAX 1007using namespace std;typedef long long LL;LL c[MAX][MAX];void init ( ){   c[0][0] = 1;   for ( int i = 1 ; i <= 1000 ; i++ )       for ( int j = 0 ; j <= i ; j++ )           if ( j== 0 || j == i ) c[i][j] = 1;           else c[i][j] = (c[i-1][j-1] + c[i-1][j])%MOD;}char s[MAX];int n;LL pow ( LL n ){    if ( n == 0L ) return 1L;    LL temp = pow ( n>>1 );    if ( n&1 ) return temp*temp%MOD*2%MOD;    else return temp*temp%MOD;}int main ( ){    init();    while ( ~scanf ( "%d" , &n ) )    {        LL ans = 0;        scanf ( "%s" , s+1 );        LL len = strlen ( s+1 );        LL sum = 0;        LL pre = 0;        for ( LL i = 1 ; i <= len ; i++ )        {            if ( s[i] == '1' )            {                LL pos = (pow ( len-i )+MOD-1)%MOD;                if ( sum == n ) ans = ( ans + pre )%MOD;                if ( sum < n && len-i-1 >= n-sum-1 )                    ans += c[len-i-1][n-sum-1]*pos%MOD,                    ans += c[len-i][n-sum]*pre%MOD;                    ans %= MOD;                sum++;                pre = (pre + (pos+1)%MOD)%MOD;            }        }        ans = ( ans + MOD )%MOD;        printf ( "%I64d\n" , ans );    }}


0 0
原创粉丝点击