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

本文解析了HDU 4704题目的核心算法思路,利用隔板原理解决数的拆分问题,并通过费马小定理进行高效模运算。提供了完整的C++代码实现。

题目链接:

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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值