The Monkey King
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem Description
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
Input
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.
1≤T≤25
1≤n,m≤100000
Output
For each case,the output should occupies exactly one line.
See the sample for more details.
Sample Input
2 2 2 3 5
Sample Output
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
题意:
要把n个桃子分给m个猴子, 其中第一个猴子的桃子要严格最多的, 问方案数。
思路:
可以枚举分多少个桃子给第一个猴子, 假设为x, 那么分给其他猴子的桃子假设为a[i], 那么a[2] + a[3] + ... + a[m-1] = n - x, 如果没有限制的话, 答案就是f(n-x, m-1), f(x, y) 表示把x个桃子分给y个猴子的方案,显然f(x, y) = C(x + y - 1, x), C是组合数,采用的是隔板法。
有限制的话, 可以根据容斥, 算出总的,然后减去1个猴子比第一个猴子的桃子多的方案,然后加上2个猴子比第一个猴子多的方案。。。
k个猴子比第一个猴子多的方案是C(m-1, k) * f(n - (k + 1) * x, m - 1)。
PS:对n件物品分给m个人,允许若干个人为空的问题,可以看成将这n件物品分成m组,允许若干组为空的问题。将n件物品分成m组,需要m-1块隔板,将这n件物品和m-1块隔板排成一排,占n+m-1个位置,从n+m-1个位置中选m-1个隔板放置即可。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#define prt(k) cout<<#k" = "<<k<<endl;
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
const int N = 201005;
void add(ll &a, ll b) { a=(a+b)%mod; }
void gcd(ll a, ll b, ll &d, ll &x, ll &y)
{
if (b==0) {
d = a; x = 1; y = 0;
} else {
gcd(b, a%b, d, y, x);
y -= a/b * x;
}
}
ll Inv(ll a)
{
ll d,x,y;
gcd(a, mod, d, x, y);
return d==1 ? (x+mod)%mod : -1;
}
ll inv[N];
ll f[N];
ll C(int n, int m)
{
if (n<0 || n<m || m<0) return 0;
return f[n] * inv[n-m] % mod * inv[m] % mod;
}
ll F(int x, int y)
{
return C(x+y-1, y-1);
}
int main()
{
f[0] = 1;
for (int i=1;i<N;i++) {
f[i] = f[i-1] * i % mod;
}
for (int i=0;i<N;i++)
inv[i] = Inv(f[i]);
int n, m; int re; cin>>re;
while (re--)
{
cin>> n>>m;
if (m==1 || n==1) { puts("1"); continue; }
ll ans = 0;
for (int x=1;x<=n;x++) {
int t = (n-x + m-2) / (m-1);
if (x <= t) continue;
for (int k=0;n-(k+1)*x>=0;k++) {
ll tmp = C(m-1, k) * F(n-(k+1)*x, m-1) % mod;
if (k%2==0) ans = (ans + tmp) % mod;
else ans = (ans - tmp + mod) % mod;
}
}
printf("%I64d\n", ans);
}
}