HDU - 5201 :The Monkey King (组合数 & 容斥)

As everyone known, The Monkey King is Son Goku. He and his offspring live in Mountain of Flowers and Fruits. One day, his sons get n peaches. And there are m monkeys (including GoKu), they are numbered from 1 to m, GoKu’s number is 1. GoKu wants to distribute these peaches to themselves. Since GoKu is the King, so he must get the most peach. GoKu wants to know how many different ways he can distribute these peaches. For example n=2, m=3, there is only one way to distribute these peach: 2 0 0.

When given n and m, you are expected to calculate how many different ways GoKu can distribute these peaches. Answer may be very large, output the answer modular 1000000007

instead.
InputThere are multiple test cases. In the first line of the input file there is an integer T indicates the number of test cases.

In the next T lines, each line contains n and m which is mentioned above.

[Technical Specification]

All input items are integers.

1T25

1n,m100000
OutputFor each case,the output should occupies exactly one line.

See the sample for more details.Sample Input
2
2 2
3 5
Sample Output
1
5


        
 
Hint
For the second case, there are five ways. They are
2 1 0 0 0
2 0 1 0 0
2 0 0 1 0
2 0 0 0 1
3 0 0 0 0
         
pro: 有N个猴子,M个桃子,其中1号的大王,所以他分得的桃要比其他猴子的都多,问有多少种法。
 
sol:由于数据不大,所以第一只猴子的个数,然后来容斥。
首先,由x个人分y个物体,可以为0,隔板法有C(x+y-1,x-1);
假设猴王的桃数位X,那么我们枚举其他猴子中分桃个数大于等于X的只书为k,那么有C(N-1,k)*(M-(k+1)*X+N-2,N-2);
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=200010;
const int Mod=1e9+7;
int N,M,fac[maxn],rev[maxn];
int C(int n,int m)
{
    if(n<0||m<0||n<m) return 0;
    return 1LL*fac[n]*rev[m]%Mod*rev[n-m]%Mod;
}
int qpow(int a,int x){
    int res=1; while(x){
        if(x&1) res=1LL*res*a%Mod;
        x>>=1; a=1LL*a*a%Mod;
    } return res;
}
int solve(int x)
{
    if(x==M) return 1;
    if(1LL*(N-1)*(x-1)<M-x) return 0;
    int res=0;
    rep(i,0,M/x){
        if(M-(i+1)*x<0) break;
        int t=1LL*C(N-1,i)*C(M-(i+1)*x+N-2,N-2)%Mod;
        if(i&1){ res-=t; if(res<0) res+=Mod;}
        else { res+=t; if(res>=Mod) res-=Mod;}
    }
    return res;
}
int main()
{
   int T,ans;
   fac[0]=1; rev[0]=1;
   rep(i,1,200000) fac[i]=1LL*fac[i-1]*i%Mod;
   rev[200000]=qpow(fac[200000],Mod-2);
   for(int i=200000-1;i>=1;i--) rev[i]=1LL*rev[i+1]*(i+1)%Mod;
   scanf("%d",&T);
   while(T--){
      scanf("%d%d",&M,&N); ans=0;
      rep(i,max(M/N,1),M) (ans+=solve(i))%=Mod;
      printf("%d\n",ans);
   }
   return 0;
}

 

 
 
 
 
 
It is your time to fight!
posted @ 2019-02-27 11:41  nimphy  阅读(298)  评论(0编辑  收藏  举报