题目大意:判断能否从黑格子走到白格子,黑白格子交替出现,左下角为黑,只能右上走。输入格子边长s,起始位置(x,y),每次移动的距离dx,dy.输出结果。
思路:直接暴力。设走了k步,如果((k*dx+x)/s + (k*dy+y)/s ) %2 == 1,且x%s!=0,y%s!=0,则可以到达白色。另外,当k=s时,显然有相当于回到了起始位置,如果没到白的显然到不了。
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
int main()
{
long long s , x , y , dx , dy;
while(cin >> s >> x >> y >> dx >> dy &&(s || x || y || dx || dy))
{
if(dx % s == 0 && x % s == 0 || dy % s == 0 && y % s == 0)
{
printf("The flea cannot escape from black squares.\n");
continue;
}
long long cur_x , cur_y ;
cur_x = x / s + 1;
cur_y = y / s + 1;
int flag = 0;
int sum = 0;
while(sum <= 2 * s) //结束条件至关重要,找遍所有的可能没有找到 ,2*s步进入下一个循环
{
if((cur_x + cur_y) % 2 && x % s != 0 && y % s != 0)
{
flag = 1;
break;
}
x += dx;
y += dy;
cur_x = x / s + 1;
cur_y = y / s + 1;
sum ++ ;
}
if(flag) printf("After %d jumps the flea lands at (%lld, %lld).\n" , sum , x , y);
else printf("The flea cannot escape from black squares.\n");
}
}