杭电ACM 新生晚会

来源:百度知道 编辑:UC知道 时间:2024/07/12 14:44:29
http://acm.hdu.edu.cn/showproblem.php?pid=2519
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
int main()
{
int t,n,m;//t组测试,n个人,选m个
cin>>t;
while(t--)
{
int temp1=1,temp2=1;
cin>>n>>m;
if(m>n)
cout<<"0"<<endl;
else if(m==n||m==0)
cout<<"1"<<endl;
else
{
if(m>n-m)
m=n-m;
for(int i=1;i<=m;i++)
{
temp1=temp1*n;
temp2=temp2*i;
n--;
}
cout<<temp1/temp2<<endl;
}

}
return 0;
}我的代码,哪里有错啊

对于N=30, M=15,你的程序肯定求出错误答案,不信你用计算器试试。
因为你的中间步骤,temp1=temp1*n会溢出。

网上有求组合数的模板,你不妨找一下,用起来又方便又正确。

#pragma warning(disable:4786)
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
int ans [ 31 ][ 31 ] ;
int main()
{
int n , m , time ;
int s( int n , int m ) ;
memset( ans , -1 , sizeof(ans) ) ;
for ( n = 0 ; n <= 30 ; ++n ) ans [ n ][ 0 ] = 1 ;
for ( n = 1 ; n <= 30 ; ++n ) ans [ n ][ 1 ] = n ;
s ( 20 , 5 ) ;

cin >> time ;
while ( time-- )
{
cin >> n >> m ;
if ( n < m )
cout << "0" << endl ;
else
if ( m == 1 )
cout << m << endl ;
else
cout << s ( n , m ) << endl ;

}
return 0;
}
int s( int n , int m )
{
if ( m == n ) return 1 ;
if ( m > n/2