题目链接:http://lightoj.com/volume_showproblem.php?problem=1067
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 |
题目大意:就是求组合数 C (m, n)
解析: 由于数据比较多,用普通方法,先除再乘,运用循环,会 TLE 或者 WA, 会爆 long long, 所以打表就很好的解决了这个问题,
打一个 1e6 的阶乘表, 由于 % 1000003., 所以不会爆,然后就是运用 C (m, n) = n ! / (n - m ) ! / m ! ,又因为是除法,
故运用乘法逆元 (不知道的, 自己百度下)去解
代码如下:
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#define N 1000009
using namespace std;
const int inf = 0x3f3f3f3f;
const int mod = 1000003;
long long dp[N];
void e_gcd(long long a, long long b, long long &x, long long &y)
{
if(b == 0)
{
x = 1; y = 0;
return ;
}
e_gcd(b, a% b, x, y);
int tm = x; x = y;
y = tm - a / b * y;
}
int main()
{
int t, cnt = 0;
long long m, n, ans, i, k, x, y;
dp[0] = dp[1] = 1;
for(i = 2; i <= 1000000; i++)
{
dp[i] = (dp[i - 1] * i) % mod;
dp[i] %= mod;
}
cin >> t;
while(t--)
{
scanf("%lld%lld", &n, &m);
if(m == n || m == 0)
{
printf("Case %d: %lld\n", ++cnt, 1);
continue;
}
e_gcd(dp[m], mod, x, y);
x = ((x % mod) + mod) % mod;
ans = x * dp[n] % mod;
e_gcd(dp[n - m], mod, x, y);
x = ((x % mod) + mod) % mod;
ans = ans * x % mod;
printf("Case %d: %lld\n", ++cnt, ans % mod);
}
return 0;
}