POJ-1942-Paths on a Grid-组合水题

本文探讨了组合数计算的方法,特别关注了优化算法在处理特定数据情况下的应用。通过实例展示了如何有效利用数学特性来简化计算过程,并提供了实用的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 http://poj.org/problem?id=1942
求C(n+m,n)
这题数据有点特殊....

C(a,b)的b 取min(b,a-b)就能ac了。。。

求组合只能实打实边乘边除了。。用ll或double足矣

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <iostream>
using namespace std;  
__int64 inf=15;
double eps=0.000001;    

__int64 C(__int64 a,__int64 b)
{
	__int64 ans=1;
	if (b<a-b) b=a-b;
	__int64 i;  
	__int64 tmp=a-b;
	for (i=a;i>b;i--)
	{
		ans*=i;
		while(tmp>1&& ans%tmp==0 )
		{ans/=tmp;tmp--;}
	}

return ans;
}
int main() 
{ 
	__int64 n,m;
	while(scanf("%I64d%I64d",&n,&m)!=EOF)
	{
		if (!n&&!m) break;
		__int64 ans=1;
		__int64 tmp=n+m; 
		ans=C(tmp,n);  
		printf("%I64d\n",ans);
	}
	
	return 0;
}



double:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <iostream>
using namespace std;  
__int64 inf=15;
double eps=0.000001;    

__int64 C(__int64 a,__int64 b)
{
	double  ans=1;
	if (b<a-b) b=a-b;
	__int64 i;  
	__int64 tmp=a-b;
	for (i=a;i>b;i--)
	{
		ans*=i;
		while(tmp>1&& (__int64)(ans)%tmp==0 )
		{ ans=ans/ (double)tmp;
		ans=(__int64)(ans+0.5);tmp--;}
	}
	
	return (__int64)(ans+0.5);
}
int main() 
{ 
	__int64 n,m;
	while(scanf("%I64d%I64d",&n,&m)!=EOF)
	{
		if (!n&&!m) break;
		__int64 ans=1;
		__int64 tmp=n+m; 
		ans=C(tmp,n);  
		printf("%I64d\n",ans);
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值