#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?
输入
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
题目链接:
http://hihocoder.com/problemset/problem/1584
题目大意:
一个n*m的格子图,一个球从(1,1)开始延右下45°走,遇到边就反弹,直到走到四个角之一停止,问一路上只经过1次的格子数。
(n,m<=109)
题目思路:
【数学规律】
首先,由于反弹特性,我把球从网格中移到网格格线的交点上,于是图成了(n-1)*(m-1)的网格,球为点,左上角为(0,0)右下角为(n-1,m-1)
然后将反弹操作变换成将网格对称折叠复制,如下图,这样就能知道,最后球停下来的时候一定位于([n-1,m-1],[n-1,m-1])([]为最小公倍数)
所以我们知道了球一路上经过的格子总数为[n-1,m-1]+1((0,0)也要考虑),令d=gcd(n-1,m-1)
再看重复经过的点,发现分别是d,2d,3d,...,其中还要扣掉位于边缘处的点(边缘处的点只可能经过一次)
也就是扣掉(n-1),2(n-1),...,和(m-1),2(m-1),..
所以总共经过多次的格子数为[n-1,m-1]/d-(n-1)/d-(m-1)/d+1(+1是因为(n-1,m-1)这个点不能算,不会出现重复扣是因为第一次重复的点就是终点)
最终答案就是[n-1,m-1]+1-([n-1,m-1]/d-(n-1)/d-(m-1)/d+1)
/**************************************************** Author : Coolxxx
Copyright 2017 by Coolxxx. All rights reserved.
BLOG : http://blog.csdn.net/u010568270 ****************************************************/
#include<bits/stdc++.h>
#pragma comment(linker,"/STACK:1024000000,1024000000")
#define abs(a) ((a)>0?(a):(-(a)))
#define lowbit(a) (a&(-a))
#define sqr(a) ((a)*(a))
#define mem(a,b) memset(a,b,sizeof(a))
const double EPS=0.00001;
const int J=;
const int MOD=;
const int MAX=0x7f7f7f7f;
const double PI=3.14159265358979323;
const int N=;
using namespace std;
typedef long long LL;
double anss;
LL aans;
int cas,cass;
int n,m,lll,ans;
LL gcd(LL a,LL b)
{
if(!b)return a;
return gcd(b,a%b);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt","r",stdin);
// freopen("2.txt","w",stdout);
#endif
int i,j,k;
int x,y,z;
// for(scanf("%d",&cass);cass;cass--)
// init();
// for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
while(~scanf("%d",&n))
{
scanf("%d",&m);
n--,m--;
LL d=gcd(n,m);
aans=1LL*n*m/d;
aans=aans-aans/d+n/d+m/d;
printf("%lld\n",aans);
}
return ;
}
/*
// //
*/