虽然这是一道水题,不过这道c(n,m)%mod 的模板值得记录
#includeusing namespace std;typedef long long ll;const int mod=1e9+7;const int maxn = 2000 + 5;int F[maxn], Finv[maxn], inv[maxn];void init(){ inv[1] = 1; for(int i = 2; i < maxn; i ++) { inv[i] = (mod - mod / i) * 1ll * inv[mod % i] % mod; } F[0] = Finv[0] = 1; for(int i = 1; i < maxn; i ++) { F[i] = F[i-1] * 1ll * i % mod; Finv[i] = Finv[i-1] * 1ll * inv[i] % mod; }}int comb(int n, int m) //comb(n, m)就是C(n, m){ if(m < 0 || m > n) return 0; return F[n] * 1ll * Finv[n - m] % mod * Finv[m] % mod;}int main(){ int t; init(); scanf("%d",&t); while(t--) { int n,m; scanf("%d%d",&n,&m); printf("%d\n",comb(max(n,m),min(n,m))); }}
也可以用dp做,记录一个递推公式 c(n,m)=(c(n-1,m-1)+c(n-1,m))%mod;
#include#include #include #define LL long longusing namespace std;const int mod=1000000007;int T,n,m,ans;LL c[1005][1005];LL C(int x,int y){ if(y==x||y==0)return 1; if(y==1)return x; if(c[x][y])return c[x][y]%mod; c[x][y]=(C(x-1,y-1)+C(x-1,y))%mod; return c[x][y];}int main(){ scanf("%d",&T); while(T--){ scanf("%d %d",&n,&m); printf("%I64d\n",C(max(n,m),min(n,m))); } return 0;}