码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4704 Sum (隔板原理 + 费马小定理)

时间:2015-01-25 22:35:27      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:

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


题意:

给定一个数n 将其分解,Si 表示将n拆成i个数的方案数

求sum( si ) 1<=i<=n;


分析:

隔板原理,  n个木棍,n-1个缝,

分成1份则是C(n-1,0);

分成2份则是C(n-1,1);

分成3份则是C(n-1,2);

...

分成n份则是C(n-1,n-1);

ans = sum( C(n-1,i) )   (0<=i<=n-1)

      =2^(n-1);

由于要取模 而且 2 与 mod 互质 ,因此可以用费马小定理来降幂 


代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

typedef long long LL;
const int mod = 1e9+7;
const int maxn = 1e5+10;

char a[maxn];

LL quick_mod(LL a,LL b,LL m)
{
    LL ans = 1;
    while(b){
        if(b&1){
            ans = ans * a % m;
            b--;
        }
        b>>=1;
        a = a * a % m;
    }
    return ans ;
}

LL change(char *s, LL m )
{
    LL ans = 0;
    int len = strlen(s);
    for(int i = 0; i < len; i++){
        ans = (ans * 10 + a[i] - '0')%m;
    }
    return ans ;
}
int main()
{
    while(~scanf("%s",a)){
        int m = mod - 1;
        LL n = change(a,m);
        printf("%I64d\n",quick_mod(2,(n-1+m)%m,mod));

    }
    return 0;
}






HDU 4704 Sum (隔板原理 + 费马小定理)

标签:

原文地址:http://blog.csdn.net/bigbigship/article/details/43120669

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!