组合数学 POJ 1942 Paths on a Grid

来源:互联网 发布:手机淘宝 没有链接 编辑:程序博客网 时间:2024/04/30 03:21

Description

Imagine you are attending your math lesson at school. Once again, you are bored because your teacher tells things that you already mastered years ago (this time he’s explaining that (a+b)2=a2+2ab+b2). So you decide to waste your time with drawing modern art instead.

Fortunately you have a piece of squared paper and you choose a rectangle of size n*m on the paper. Let’s call this rectangle together with the lines it contains a grid. Starting at the lower left corner of the grid, you move your pencil to the upper right corner, taking care that it stays on the lines and moves only to the right or up. The result is shown on the left:

Really a masterpiece, isn’t it? Repeating the procedure one more time, you arrive with the picture shown on the right. Now you wonder: how many different works of art can you produce?
Input

The input contains several testcases. Each is specified by two unsigned 32-bit integers n and m, denoting the size of the rectangle. As you can observe, the number of lines of the corresponding grid is one more in each dimension. Input is terminated by n=m=0.
Output

For each test case output on a line the number of different art works that can be generated using the procedure described above. That is, how many paths are there on a grid where each step of the path consists of moving one unit to the right or one unit up? You may safely assume that this number fits into a 32-bit unsigned integer.
Sample Input

5 4
1 1
0 0
Sample Output

126
2

题目大意
一个长宽为 a、b 的网格矩形,要求从左下角抵达右上角,每次可以有右和上两个方向,可以走任意个格子。输出有多少种抵达的办法。

解题思路
因为长宽分别为 a,b,暂且设 a 为长,则一共有 a+b 步,其中 a 步向右走,b步向上走,有点像初高中做的题 ,方法共有 c[a+b][b] 种。关键是如何求这个组合数了。对于c[m][n],即是在求 n!/(m!(n-m)!),仔细一点可以发现分母上的 m! 可以与分子上 n! 的后 m 位约分,留下 n! 的前(n-m)位除以 (n-m)!。如 c[7][3] =7!/(3!*4!)= (7*6*5*4)/(4*3*2*1)=(7/4)(6/3)(5/2)(4/1)①,即分成两两相除的格式。
根据①式,若从前往后进行求商累乘,每一步不一定整除,所以需要用 double 类型,我的代码就是这种;若从后往前进行求商累乘,直接用整型就好了,因为每一步求出来的都是一个组合数必为正数。
另外很坑的一点,就是存在一边为 0 的情况,只有 0 0 才结束输入。好好审题啊,wa跪了一条街,跪到怀疑自己的智商:(

代码实现

#include <iostream>#include<cstdio>using namespace std;int main(){    __int64 a,b;    while(~scanf("%I64d%I64d",&a,&b))    {        if(a==0&&b==0)            break;        __int64 t,d;        t=a>b?b:a;        d=a+b;        double mul=1.0;        while(t>0)        {            mul*=double(d--)/double(t--);        }        printf("%.0f\n",mul);    }    return 0;}
0 0
原创粉丝点击