1067 - Combinations
PDF (English) | Statistics | Forum |
Time Limit: 2 second(s) | Memory Limit: 32 MB |
Given n different objects, you want to take k of them. How many ways to can do it?
For example, say there are 4 items; you want to take 2 of them. So, you can do it 6 ways.
Take 1, 2
Take 1, 3
Take 1, 4
Take 2, 3
Take 2, 4
Take 3, 4
Input
Input starts with an integer T (≤ 2000), denoting the number of test cases.
Each test case contains two integers n (1 ≤ n ≤ 106), k (0 ≤ k ≤ n).
Output
For each case, output the case number and the desired value. Since the result can be very large, you have to print the result modulo 1000003.
Sample Input | Output for Sample Input |
3 4 2 5 0 6 4 | Case 1: 6 Case 2: 1 Case 3: 15 |
PROBLEM SETTER: JANE ALAM JAN
借鉴:https://blog.csdn.net/qq_34287501/article/details/52143890?locationNum=6
#include<iostream>
#include<string>
#include<cstdio>
#define N 1000009
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1000003;
long long dp[N];
long long ex_gcd(long long a,long long b,long long &x,long long &y)
{
//a是所求数,b是模数,
// x=((x%mod)+mod)% mod; 是逆元
long long d;
if(b==0)
{x=1; y=0; return a;}
d=ex_gcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
long long C(long long n,long long m)
{
long long x,y;
long long ans;
ex_gcd(dp[m], mod, x, y);
x=((x%mod)+mod)% mod; //这样就保证是最小正数
ans=x%mod;
ex_gcd(dp[n - m], mod, x, y);
x = ((x % mod) + mod) % mod; //公式算的是一个因子的逆元,当两个因子相乘的话
ans = ans*x%mod;
ans%=mod;
ans=(ans* dp[n])% mod;
return ans;
}
int main()
{
int t, cnt = 0;
long long m,n,i;
dp[0] = dp[1] = 1; //C(n,m)公式:n!/(m!*(n-m)!)
for(i = 2; i <= 1000000; i++) //C(n,m)会爆数据什么的吧
{ //模p乘法逆元的应用:将除法mod转为乘法
// (a/b)%p==(a*b1)%p, b1为b的逆元
// (a/(b*c))%p==(a*b1*c1)%p,b1为b的逆元,c1为c的逆元
dp[i] = dp[i - 1] * (i % mod);
dp[i] %= mod; //阶乘mod的话,从1开始推的话就可以推出这个公式。
} //所以现在只要记住累乘mod两下就行
cin >> t; //就叫做阶乘模吧。。。。
while(t--)
{
scanf("%lld%lld", &n, &m);
if(m == n || m == 0) //C(m,0)==1;
{
printf("Case %d: %lld\n", ++cnt, 1);
continue;
}
printf("Case %d: %lld\n", ++cnt,C(n,m));
}
return 0;
}