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 的逆元);求逆元可以用扩欧和费马小定理(可以啊、百度的);
代码:
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; }
相关文章推荐
- 人人都能玩航拍 手把手教你装4轴
- Could not create the view: An unexpected exception was thrown.问题解决
- Android studio创建工程卡死问题
- JS高亮提示插件spket
- 关于创建String对象过程的内存分配
- ACM South American Programming Contest 2007
- menu
- 如何在指针中隐藏数据
- C#多播委托
- Hibernate 的<generator class="native"></generator>的不同属性含义
- [LeetCode]Lowest Common Ancestor of a Binary Tree
- hdu 1151 二分图最小路径覆盖
- ROS 学习系列 -- Roomba, Xtion Pro live 实现360度全景照片panorama 无法启动的解决方案
- 背单词App开发日记3
- Linux下进程的内存结构
- 多线程程序排错总结
- java的数据类型
- 程序员技术练级攻略(转)
- 开发-数据库-MongoDB初探
- 股票学习(技术指标)