Paths on a Grid

本文探讨了一个数学问题:在一个a*b的网格中,从左下角到右上角有多少种不同的行走路径。每一步只能向上或向右移动。文章提供了一种使用组合数学的方法来解决这个问题,并分享了一个具体的C++实现案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 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步向右。用数学的思路就是C上(a||b)下(a+b)来求多少种方法!有了思路做就很容易了~代码倒是很好写,但是,主要是,int类型不满足条件,虽然题目说的是32位,但是还有阶乘的存在。最好用——int64,这样可以满足条件。还有,一个我不理解的,地方,为什么C上(a||b)下(a+b)分开算总是WR,但是写在一个for()循环里就可以满足。是不是精确的问题啊,分开算上下阶乘然后相除,不够精确?!请各位大神指点~谢啦哈~大笑

#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 c,i;
		__int64 m=1,n=1,t=1;
		c=a+b;
		if(a>b)
			a=b;
		for(i=1;i<=a;i++)
		{
			t=t*c/i;
			c=c-1;
		}
		printf("%I64d\n",t);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值