#1584 : Bounce(推理题)

#1584 : Bounce

时间限制:1000ms

单点时限:1000ms

内存限制:256MB

描述

For Argo, it is very interesting watching a circle bouncing in a rectangle.

As shown in the figure below, the rectangle is divided into N×M grids, and the circle fits exactly one grid.

The bouncing rule is simple:

1. The circle always starts from the left upper corner and moves towards lower right.

2. If the circle touches any edge of the rectangle, it will bounce.

3. If the circle reaches any corner of the rectangle after starting, it will stop there.

Argo wants to know how many grids the circle will go through only once until it first reaches another corner. Can you help him?

扫描二维码关注公众号,回复: 4134701 查看本文章

输入

The input consists of multiple test cases. (Up to 105)

For each test case:

One line contains two integers N and M, indicating the number of rows and columns of the rectangle. (2 ≤ N, M ≤ 109)

输出

For each test case, output one line containing one integer, the number of grids that the circle will go through exactly once until it stops (the starting grid and the ending grid also count).

样例输入

2 2
2 3
3 4
3 5
4 5
4 6
4 7
5 6
5 7
9 15

样例输出

2
3
5
5
7
8
7
9
11
39

思路:从左上角开始,所以可以先去除左上角的行和列(这里的行列所包含的只讲过一次的方个数有(n-1)/g+(m-1)/g个),然后对剩下的(n-1)行和(m-1)列划分,

如果令tp=GCD(n-1,m-1)划分为(n-1)/g* (m-1)/g个单元,每个单元里有(g-1)个只经过一次的方格。

所以总次数是:

ans=(n-1)/g + (m-1)/g + (g-1) * (n-1)/g* (m-1)/g;

参考文章:https://blog.csdn.net/Feynman1999/article/details/78073669

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
LL gcd(LL x,LL y)
{
	return y==0?x:gcd(y,x%y);
}
int main(void)
{
	LL n,m,tp,ans;
	while(~scanf("%lld%lld",&n,&m))
	{
		tp=n<m?gcd(m-1,n-1):gcd(n-1,m-1);
		ans=(n-1)/tp+(m-1)/tp+((n-1)/tp*(m-1)/tp)*(tp-1); 
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41829060/article/details/83831767