poj 1942 走地图的组合数学

来源:互联网 发布:php 加密 beast 破解 编辑:程序博客网 时间:2024/05/18 04:01

题意:求从左下角出发只能往右走和往上走,给定矩阵n*m,求有多少中走法,组合数学,求Cn(n+m)或Cm(n+m)为了减少计算量,去小的那个,三个for肯定会爆掉,而杨辉三角规模只能20+太少
解决方法
拆分阶乘,逐项相除,再乘以前面所有项之积。这种方法用一个循环就OK了,时间复杂度只有O(n-m),非常可观。
某大牛写的函数原型:
double cnm=1.0;

while(b>0)

cnm*=(double)(a- -)/(double)(b- -);

贴上代码,必须用unsigned,否则wa。。

#include <cstdio>#include <cstring>#include <string>#include <iostream>using namespace std;unsigned comp(unsigned n,unsigned m){    unsigned a=m+n;    unsigned b=(m<n?m:n);    double cnm=1.0;    while(b>0)        cnm*=(double)(a--)/(double)(b--);    cnm+=0.5;    return (unsigned)cnm;}int main(){    unsigned n,m;    while(cin>>m>>n)    {        if(!m&&!n)            break;        cout<<comp(n,m)<<endl;    }}
0 0