lightoj 1067 - Combinations (组合数、乘法逆元)

本文提供了一种解决LightOJ 1067题的有效方法,通过预处理1e6的阶乘表,并利用乘法逆元解决大数组合问题,避免了直接运算可能产生的溢出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://lightoj.com/volume_showproblem.php?problem=1067


1067 - Combinations
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


题目大意:就是求组合数  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;
}



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值