码迷,mamicode.com
首页 > 其他好文 > 详细

light oj 1067 组合数取模

时间:2015-07-10 13:20:48      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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

题目:

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

Description:

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.

题意:给你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[n])%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;
}
View Code

 

light oj 1067 组合数取模

标签:

原文地址:http://www.cnblogs.com/2445512490wh/p/4635185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!