light oj 1102 Problem Makes Problem [组合数+逆元]

来源:互联网 发布:网络电视剧上瘾全集 编辑:程序博客网 时间:2024/05/17 07:55

Description

As I am fond of making easier problems, I discovered a problem. Actually, the problem is 'how can you make n by adding k non-negative integers?' I think a small example will make things clear. Suppose n=4 and k=3. There are 15solutions. They are

1.      0 0 4

2.      0 1 3

3.      0 2 2

4.      0 3 1

5.      0 4 0

6.      1 0 3

7.      1 1 2

8.      1 2 1

9.      1 3 0

10.  2 0 2

11.  2 1 1

12.  2 2 0

13.  3 0 1

14.  3 1 0

15.  4 0 0

As I have already told you that I use to make problems easier, so, you don't have to find the actual result. You should report the result modulo 1000,000,007.

Input

Input starts with an integer T (≤ 25000), denoting the number of test cases.

Each case contains two integer n (0 ≤ n ≤ 106) and k (1 ≤ k ≤ 106).

Output

For each case, print the case number and the result modulo 1000000007.

Sample Input

4

4 3

3 5

1000 3

1000 5

Sample Output

Case 1: 15

Case 2: 35

Case 3: 501501

Case 4: 84793457


今天终于懂了乘法逆元是用来干嘛的了, 对于加减乘法而言,过程取模是无所谓的, 但是当涉及除法的时候,就无法正常的取模,所以需要换一种思路去解决;

就好比 a/b = a * b^-1 一样, 即乘倒数, 只不过这个倒数是在取模后形成的 所以是乘法逆元;


题目大意:给你一个数字n,代表这个数为n ;给你一个k,代表拆分数的个数, 求所有的可能性;

题解:先把过程看做  x1 + x2 + x3 +...+xk = n ;  这样就变成了挡板问题 ,即:把n个物品放在m个盒子里面的方案数


如上图一般,实质就是求解 C(n+k-1,k-1)的方案数, 约定f(a)代表a的阶乘,对于组合数 C(m,n) =  f(m)/(f(n)*f(m-n));

由于避免除法,所以分别求 1/f(n) 和  1/f(m-n)的逆元, 假设 求 1/A的逆元, 由于mod是质数 。 所以由费马小定理得

A^(p-1)%p = 1 % p      --------->  两边同乘 A^-1 ----------->A^(p-2) %p = A^-1%p ; 即可得逆元 , 随后快速幂处理逆元即可

AC代码:

#include <bits/stdc++.h>#define mod 1000000007#define ll long longusing namespace std;ll a[2000000];void C(){    memset(a,0,sizeof(a));    a[0] = a[1] = 1 ;    for(int i = 2 ; i <=2000000;i++)        a[i] = a[i-1]*i%mod;}ll quick(ll a , ll b){    ll res = 1 ;    while(b)    {        if(b&1) res = res *  a %mod ;        b>>=1;        a = a * a %mod ;    }    return res ;}int main(){    int t ;    cin>>t;    C();    for(int cas = 1 ; cas<=t;cas++)    {        ll n , k ;        cin>>n>>k;        ll c = a[k-1];        ll d = a[n];        printf("Case %d: ",cas);        cout<<a[n+k-1]*quick(c,mod-2)%mod*quick(d,mod-2)%mod<<endl;    }    return 0;}



0 0