您的位置:首页 > 其它

light oj 1067 组合数取模

2015-07-24 23:21 281 查看
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.

题目连接:http://acm.hust.edu.cn/vjudge/problem/visitOriginUrl.action?id=26784

题目:

Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu

题意:给你n和k,从n个different objects,选k个不同的,就是求组合数C(n,k)%1000003;

分析:

时间只有2秒,T组测试数据加上n的106达到了109递推肯定超时,那么考虑组合公式,C(n,k)=n!/(k!*(n-k)!);先打一个阶乘的表(当然要取模,只有106),然后就是这个除法取模的问题,当然是求逆元,(a/b)%mod=a*(b对mod 的逆元);求逆元可以用扩欧和费马小定理(可以啊、百度的);



代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=1e6+5,mod=1000003;
typedef long long LL;
LL fact[maxn];
void f()
{
    fact[1]=fact[0]=1;
    for(int  i=2;i<maxn;i++)
        fact[i]=(LL)(i*fact[i-1])%mod;
}
LL niyuan(LL a,LL p)//就是个快速幂
{
    if(p==0)return 1;
    LL x=niyuan(a,p/2);
    LL ans=x*x%mod;
    if(p%2==1)ans=ans*a%mod;
    return ans;
}
LL c(int n,int k)
{
    LL fm=(fact[k]*fact[n-k])%mod;
    LL ans1=niyuan(fm,mod-2);//费马小定理,求一个幂就好;
    return (ans1*fact
)%mod;
}
int main()
{
    int t,n,k,kase=0;
    f();//打表
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        if(k*2>n)
            k=n-k;//组合数对称性,减少计算;
        printf("Case %d: %lld\n",++kase,c(n,k));
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: