Mind control
There is a wonderful country where people like eating very much. Each person has exactly one direct follower while the follower's follower is also follower of this man (of course the most unattractive man doesn't have his follower).
And you find some amazing cake, if you give it to a person, you can have the trust of this person and all his followers.
Now you want to give out M cakes randomly to N person (each person can get at most one cake), please calculate the expectation of the trust you have earned.
Because the answer can write as a / b, please output a * b^-1 mod 10^9 + 7. (b * b^-1 ≡ 1 mod 10^9 + 7)
Input
First line a single integer T indicating the number of cases. T<=1000000;
For each case, first line two number N and M described before. N, M<=1000000;
Output
A single integer indicating the expectation of the trust you have earned. (mod 1e9 + 7)
Sample Input
2
3 3
3 2
Sample Output
3
666666674
Hint
For case 2, you can give cake to person 1 and 2 or to person 1 and 3 or to person 2 and 3, so answer = 3 * 1 / 3 + 3 * 1 / 3 + 2 * 1 / 3 = 8 / 3
题意:有N个人,N-1个人都有一个追随者且追随者关系为链状(即为一条长度为N的链),有M个蛋糕,随机的分配给M个人(每个人最多只能得到1个),分配给某个人就能得到这个人以及其追随者的信任,问信任的期望值为多少,假设结果为x/y的形式,输出为x*y^(-1),y*y^(-1)%(1e9+7)=1|,即y^(-1)为y相对于(1e9+7)的逆元。(T组数据 ,T,N,M<=1e6)
思路:这是一个纯数学问题。。。奈何我是一名数学蒟蒻相信挺多人和我一样,只写出一部分。即 。而且 也肯定知道 这个是不能直接算的,因为 T N M 都是1e6 的数,显然会T. 就表示很无奈了。下面给出大牛的推算式子。
后面的和式为一个组合恒等式,根据C(m,m)=C(m+1,m+1)以及C(m+1,m)+C(m+1,m+1)=C(m+2,m+1)可得证明:
所以几个式子合并有:
。看见了介个,是不是觉得,代码.... 无太大难度。。。。 表示对数学感到深深的无奈。。
AC代码:
#include<cstdio>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
ll quick(ll a,ll b,ll p){
ll ans = 1;
while(b){
if(b & 1) ans = ans * a % p;
a = a * a % p;
b = b / 2;
}
return ans;
}
ll niYuan(ll a,ll b){
return quick(a,b - 2,b);
}
int main()
{
int t; scanf("%d",&t);
while(t --){
int n,m; scanf("%d%d",&n,&m);
if(m > n) printf("%d\n",n);
else {
long long fz = (ll)m * (ll)(n + 1) % mod;
long long fm = m + 1;
printf("%I64d\n",fz * niYuan(fm,mod) % mod);
}
}
return 0;
}