ACM-ICPC 2018 焦作赛区网络预赛 G. Give Candies [ 费马小定理 + 快速幂 + 大数 ]

14 篇文章 0 订阅
7 篇文章 0 订阅

题目链接:

ACM-ICPC 2018 焦作赛区网络预赛 G. Give Candies

题意概括:

有 n 个同学,学号是 1 至 n 。有 n 颗糖,随机分给这些同学(有的同学可能分不到糖),问有多少种分法

数据范围:

1\leq T\leq 100

1\leq N\leq 100^{100000}

题解分析:

先求出公式:

从 n 个同学中取 k 人,表示可以分到糖的同学,方法数是 C_n^k

接下来要把 n 块糖分给这 k 个人,并且要保证每人至少有 1 颗。这里就要用隔板法的思想了,方法数是 C_{n-1}^{k-1}

可以得到总的方法数:

\sum^n_{ k = 1 }C_n^kC_{n-1}^{k-1}

通过牛顿二项式定理,我们可以把这个式子转化成  2^{n-1}

就得到了最终的公式。但是遇到了一个问题,就是 n 的值太大了,只能用字符串读入,就算用快速幂也会TLE

这里就需要用到费马小定理,把 n 降到一个可计算的值

由于 2 与 1000000007 互质,所以满足

2^{1000000007-1}\equiv 1\, \, \, (mod \, \, 1000000007)

2^{n \, \, \, mod\, \, 1000000006}= 2^{n} \, \, \, (mod \, \, 1000000007)

所以只需要用大数类读入 n ,对 1e9 + 6 取模后用快速幂求出来就好了 

AC代码:

#include <stdio.h>
#include <string.h>
#include <memory.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
const int mod = 1e9 + 7;
char str[maxn];
int n[maxn];

ll mod_mult(ll a, ll b, ll mod) {
    a %= mod;
    b %= mod;
    ll ans = 0;
    while (b > 0) {
        if (b & 1) {
            ans += a;
            if (ans >= mod)
                ans -= mod;
        }
        a <<= 1;
        if (a >= mod) a = a - mod;
        b >>= 1;
    }
    return ans;
}

ll mod_pow(ll x, ll n, ll mod) {
    if (n == 0) return 1;
    ll res = mod_pow(mod_mult(x , x , mod), n / 2, mod);
    if (n & 1) res = mod_mult(res , x , mod);
    return res;
}

ll Cut() {
    int len = (int)strlen(str);
    for(int i = 0; i < len; i++)
        n[i] = str[i] - '0';
    ll ans = 0;
    for(int i = 0; i < len; i++)
        ans = (ans * 10 + n[i]) % (mod - 1);
    return ans;
}

int main() {
    int T;
    scanf("%d", &T);
    while(T--) {
        scanf("%s", str);
        ll res = Cut();
        if(res == 0)
            printf("1\n");
        else
            printf("%lld\n", mod_pow(2, res - 1, mod));
        memset(n, 0, sizeof(n));
        memset(str, 0, sizeof(str));
    }
    return 0;
}

 

                                                       Give Candies

There are N children in kindergarten. Miss Li bought them N candies. To make the process more interesting, Miss Li comes up with the rule: All the children line up according to their student number (1...N ), and each time a child is invited, Miss Li randomly gives him some candies (at least one). The process goes on until there is no candy. Miss Li wants to know how many possible different distribution results are there.

Input

The first line contains an integer T , the number of test case. The next T lines, each contains an integer N .

1\leq T\leq 100

1\leq N\leq 100^{100000}

Output

For each test case output the number of possible results (mod 1000000007).

样例输⼊

1
4

样例输出

8

题目来源

ACM-ICPC 2018 焦作赛区网络预赛

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值