ACM: 一题组合数学题 poj1942 (细…

来源:互联网 发布:淘宝网店加盟哪家好 编辑:程序博客网 时间:2024/05/18 22:16

                                                                  Paths on a Grid

Description

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

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

ACM: <wbr>一题组合数学题 <wbr>poj1942 <wbr>(细节题)


Really a masterpiece, isn't it? Repeating the procedure one moretime, you arrive with the picture shown on the right. Now youwonder: how many different works of art can you produce?

Input

The input contains several testcases. Each is specified by twounsigned 32-bit integers n and m, denoting the size of therectangle. As you can observe, the number of lines of thecorresponding grid is one more in each dimension. Input isterminated by n=m=0.

Output

For each test case output on a line the number of different artworks that can be generated using the procedure described above.That is, how many paths are there on a grid where each step of thepath consists of moving one unit to the right or one unit up? Youmay safely assume that this number fits into a 32-bit unsignedinteger.

Sample Input

5 4

1 1

0 0

Sample Output

126

2

 

题意: 从左下角走向右上角 , 每次只可以向上 or 右. 问结果可以有多少种走法. 

思路:

                 组合数学, 走m+n步, 当n步走 '上' 就有m步走 '右'. 中学组合数学题.

                 (打杨辉三角表会超时的. 时间O(n^2)毕竟时间挺可观的.-。-!!)

代码:

#include <cstdio>
#include <iostream>
using namespace std;

__int64 result(__int64 n , __int64 m)
{
     int i;
     double ans = 1.0;
     for(i = 0; i < m; ++i)
    {
            ans *= (double) (n-i) / (m-i);
     }

      return ans+0.5;
}

int main()
{
     __int64 m , n ;
     while(scanf("%I64d%I64d",&m,&n) != EOF)
    {
            if(m == 0 && n == 0)
                break;
           __int64 min = m > n? n : m;
           __int64 res = result(m+n,min);

          printf("%I64d\n",res);
     }

     return 0;
}

0 0