每个测试文件均包含多组测试数据。第一行输入一个整数
代表数据组数,每组测试数据描述如下:
在一行上输入六个整数
代表目标位置所在坐标、向上下左右四个方向单次移动的步数。
对于每一组测试数据,新起一行。如果小红可以到达目标位置,输出
;否则,直接输出
。
3 1 1 1 1 1 1 3 3 6 6 6 6 5 1 1 1 1 3
YES NO YES
对于第一组测试数据,其中一种可行的方案是,向上移动
步到达
,然后向右移动
步到达
。
对于第二组测试数据,我们可以证明,小红无法通过给定的步数到达
。
对于第三组测试数据,其中一种可行的方案是,向右移动
步到达
、向左移动
步到达
、向右移动
步到达
、最后向上移动
步到达
。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
while (T-- > 0) {
long x = scanner.nextLong();
long y = scanner.nextLong();
long a = scanner.nextLong();
long b = scanner.nextLong();
long c = scanner.nextLong();
long d = scanner.nextLong();
// 计算y方向所需的最大公约数
long gcdY = gcd(a, b);
// 计算x方向所需的最大公约数
long gcdX = gcd(c, d);
// 判断y是否是gcd(a,b)的倍数,且x是否是gcd(c,d)的倍数
if (y % gcdY == 0 && x % gcdX == 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
scanner.close();
}
// 欧几里得算法计算最大公约数
private static long gcd(long a, long b) {
while (b != 0) {
long temp = b;
b = a % b;
a = temp;
}
return a;
}
}
看懂规律后实际上是比较简单的题,求最大公约数gcd的题,
我们可以无数次根据规定步数向上下左右走,竖直方向所能到达的地方是单次往上下方向走的最大公约数的倍数,
左右方向所能到达的地方是左右的最大公约数的倍数。
比如3和5,最大公约数是1,任何方向都能到达。2和8,最大公约数是2,任何2的倍数位置都能到达,比如-4 -2 0 2 4.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int T = in.nextInt();
for (int i = 0; i < T; i++) {
int leftRight = in.nextInt();
int upDown = in.nextInt();
int up = in.nextInt();
int down = in.nextInt();
int left = in.nextInt();
int right = in.nextInt();
int shangXia = gcd(Math.abs(up), Math.abs(down));
int zuoYou = gcd(Math.abs(left), Math.abs(right));
if ((upDown % shangXia == 0) && (leftRight % zuoYou == 0)) {
System.out.println("YES");
} else System.out.println("NO");
}
}
}
private static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
}