51nod 1251 Fox序列的数量 (容斥)
枚举最多数字的出现次数$k$, 考虑其他数字的分配情况.
对至少$x$种数出现$\ge k$次的方案容斥, 有
$\sum (-1)^x\binom{m-1}{x}\binom{n-(x+1)k+m-2}{m-2}$.
暴力枚举$k$和$x$, 复杂度是$O(nlogn)$
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl '\n' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 1e6+10; int n, m; ll fac[N], ifac[N]; ll C(int n, int m) { return fac[n]*ifac[n-m]%P*ifac[m]%P; } int main() { fac[0]=ifac[0]=1; REP(i,1,N-1) fac[i]=fac[i-1]*i%P,ifac[i]=inv(fac[i]); int t; scanf("%d", &t); REP(i,1,t) { scanf("%d%d", &n, &m); if (m==1) {puts("1");continue;} int ans = 0; REP(k,1,n) REP(x,0,m-1) { ll p = n-(ll)(x+1)*k+m-2; if (p<m-2) break; int ret = C(p,m-2)*C(m-1,x)%P; if (x&1) (ans-=ret)%=P; else (ans+=ret)%=P; } ans = (ll)ans*m%P; if (ans<0) ans+=P; printf("%d\n", ans); } }