ACM-ICPC 2018 焦作賽區網絡預賽 G. Give Candies [ 費馬小定理 + 快速冪 + 大數 ]

題目鏈接:

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 焦作賽區網絡預賽

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章