Binomial Showdown(组合计数模板)


Link:http://poj.org/problem?id=2249


Binomial Showdown
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 18459   Accepted: 5635

Description

In how many ways can you choose k elements out of n elements, not taking order into account? 
Write a program to compute this number.

Input

The input will contain one or more test cases. 
Each test case consists of one line containing two integers n (n>=1) and k (0<=k<=n). 
Input is terminated by two zeroes for n and k.

Output

For each test case, print one line containing the required number. This number will always fit into an integer, i.e. it will be less than 2 31
Warning: Don't underestimate the problem. The result will fit into an integer - but if all intermediate results arising during the computation will also fit into an integer depends on your algorithm. The test cases will go to the limit. 

Sample Input

4 2
10 5
49 6
0 0

Sample Output

6
252
13983816

Source

Ulm Local 1997


题意&解题思路:计算组合数c(n,m)


AC  code:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<vector>
#define LL long long
#define MAXN 1000100
using namespace std;
LL n,m;
LL Cnm(LL n,LL m)//计算组合数C(n,m) 
{
	if(m>n/2)//根据组合公式,可以减少枚举量 
	m=n-m;
	LL a=1,b=1;
	for(int i=1;i<=m;i++)//顺序进行m次运算 
	{
		a*=n+1-i;//计算前i项运算结果的分子a和分母 b 
		b*=i;
		if(a%b==0)
		{
			a/=b;
			b=1;
		}
	}
	return a/b;
}

int main()
{
	while(cin>>n>>m)
	{
		if(n==0&&m==0)
			break;
		cout<<Cnm(n,m)<<endl;
	}
	return 0;
 } 



你可能感兴趣的:(优化,算法,ACM)