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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值