1. 程式人生 > >poj 1942 Paths on a Grid(組合數模板)

poj 1942 Paths on a Grid(組合數模板)

題意:給你一個n*m的矩陣,問從左下角走到右上角有多少種方式? 只可以往右或上走。


解析: 容易看出,只有一列直線時,向上有n條線段可以選,每增加一列,可以增加一條線段選擇,即答案為c(n+m,n)

求解 c(n+m,n) 時,可以直接套模板

__int64 C(__int64 m, __int64 n){
    if(m > n - m) m = n - m;
    __int64 ans = 1, cou = m;
    while(cou --){
        ans *= n --;
        while(ans % m == 0 && m > 1)
            ans /= m --;
    }
    return ans;
}


由於資料水,直接模擬可以過

#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;

typedef long long  LL;

LL C(LL n,LL m)
{
     LL res=1;
    if(m>n-m) m=n-m;
    for(int i=1;i<=m;i++)
    {
        res=res*(n-i+1)/i;
    }
    return res;
}
int main()
{
    LL n,m;
    while(~scanf("%lld%lld",&n,&m)&&(n+m))
    {
        printf("%lld\n",C(n+m,n));
    }
    return 0;
}