1. 程式人生 > >POJ - 1942 Paths on a Grid (組合數學)

POJ - 1942 Paths on a Grid (組合數學)

POJ - 1942 Paths on a Grid (組合數學)

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=a 2+2ab+b 2). 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

  • 題目大意:
    給你一個方陣,讓你從左下角走到右上角,每次只能向右走或者向上走,問有多少種走法。
    輸入 n,m是大小n*m的網格 輸出走法的數目。
  • 解題思路:
    (首先明確一點,這個題肯定不能用dfs的 因為資料量太大了)
    因為每次能能往上或者往右,所以它一共需要走n+m步,所以答案就是C(n+m,m),接下來就是如何求C(n+m,m)的問題了,可以用時間複雜度是m的演算法來求:
int fun(int n,int m)///求組合數
{
	double s=1.0;
	for(int i=1;i<=m;i++)
	{
		s*=double(n-i+1)/double(i);
	}
	s+=0.5;///必去四捨五入 否則就wa
	return  (int)s;
}

有幾個小細節的地方需要注意,這個題賊坑。。。
1.n,m是無符號整數,不是整數,寫成int 就過不了,因為int比 無符號的int 少一位數值位,表示的數要少一些。
2.在求組合數的函式中必須四捨五入,否則會wa…我也不知為啥。。
3.C(n+m,n)和 C(n+m,m)相等的 但是你要選一個n,m中較小的一個,不加這條判斷好像會超時。。。。

  • 完整程式碼如下:
#include <iostream>
#include <cstdio>
#define ll long long
#define ui unsigned 
using namespace std;
ui n,m;
void swap(ui &a ,ui &b)
{
	ui t=a;
	a=b;
	b=t;
	return ;
 } 
ui fun(ui n,ui m)///求組合數
{
	double s=1.0;
	for(ui i=1;i<=m;i++)
	{
		s*=double(n-i+1)/double(i);
	}
	s+=0.5;
	return  (ui)s;
}
int main()
{
	while(cin>>n>>m)
	{
		if(n==0&&m==0)
			break;
		//cout<<fun(n+m,n)<<endl;
		if(n>m)
			swap(n,m);
		cout<<fun(n+m,n)<<endl;
	}
	return 0;
}