Paths on a Grid(POJ--1942

来源:互联网 发布:伤感的网络歌曲有哪些 编辑:程序博客网 时间:2024/05/16 15:52

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.
题意:给你一个方格,起点是该方格的左下点,终点是该方格的右上点,路线只能是沿着方格的边横着向右或竖着向上走,求从起点到终点的路线数。
思路:其实之前我们做过这一类题,是用递推做的,当时的数据n,m<=20,可以直接用递推数组做,而此题的数据n,m<=2^32-1,不能再用递推数组求解。仔细观察该方格的路线方案你会发现你要走的边总共只有n+m条,这n+m条你要么横着走要么竖着走,那么该题理所当然就会想到用组合数学来做。另一个问题就是,组合数组也开不了那么大,那么只能用计算算法来算组合数了。c(n,m)=n*(n-1)*---*(n-m+1)/m*(m-1)*---*1=(n/m)*((n-1)/(m-1))*---*((n-m+1)/1),即求组合数的计算方法就是累乘。由于累乘得出的数会很大很大,连long long 型都会超,那么就定义成double型,对于double型数,如果其没有小数则整数部分会能达到很大。

Sample Input

5 41 10 0

Sample Output

1262

#include <cstdio>#include <cmath>#include <algorithm>#define MAX 32000using namespace std;int main(){    double n,m,t;    while(~scanf("%lf %lf",&n,&m))      //double型用%lf输入    {        if(n==0&&m==0)            break;        if(m>n)                    //找出最小的那个数,根据最小数进行累乘,可以相对减少一下循环次数        {            t=m;            m=n;            n=t;        }        double sum=1;        for(double i=1; i<=m; i+=1)    //对于double型,i++之后得到的i不一定是原数加1,合理的做法是让其直接+1,i--同理        {            sum*=(i+n)/i;               //经过观察会发现组合数所有累乘的分数分子与分母之差都相等        }        printf("%.0f\n",sum);        //不管是float型还是double型数,合法输出都应该是%.位数(要求输出的小数位数)f而不是%.位数lf//        printf("%.0lf\n",sum);      //在有些情况下double型用%.位数lf输出是合法的【在poj中,如果用c++交,此句是对的,如果是用g++交,此句就是错的】    }    return 0;}<strong></strong>


0 0
原创粉丝点击