首页 > 试题广场 >

行走

[编程题]行走
  • 热度指数:471 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
小美正在一个无限大的二维坐标轴上运动,初始时她位于坐标 (x,y)

她将基于一个由 n 个整数组成的数组 \{a_1, a_2, \dots, a_n\} 进行移动,对于第 i 次移动,她都需要选择这样两个整数 lr,满足 |l| + |r| = a_i,随后移动到 (x + l, y + r) 这个位置。

现在请问,n 次移动后,她能否恰好移动到 (p,q) 这个位置。

输入描述:
第一行一个整数 t(1\leq t\leq 1000),表示数据组数。对于每组数据格式为:
第一行一个整数 n(1\leq n\leq 10^5),表示数组长度。
第二行 n 个整数,第 i 个整数为 a_i(0\leq a_i\leq 1),表示每次移动的距离。
第三行四个整数 x,y,p,q(-10^{18}\leq x,y,p,q\leq 10^{18}),分别表示起点的横纵坐标,终点的横纵坐标。
数据保证单个测试文件 \sum n\leq 10^5


输出描述:
对于每组数据输出一个字符串,若可以恰好移动到 (p,q) 输出 "YES" ,否则输出"NO"。
示例1

输入

2
2
0 0
1 1 1 1
3
1 1 1
1 1 2 2

输出

YES
NO
0≤ ai ≤1,ai 仅取0、1
发表于 2025-07-10 15:07:27 回复(0)
需要考虑:坐标来回移动 的场景,即:向前移动一步,然后向后移动一步,统计移动了两步,但是坐标值没有变。
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int t = in.nextInt();
            in.nextLine();
            for(int i = 0;i < t;i++){
                int n = in.nextInt();
                in.nextLine();
                long num1 = 0;
                for(int j = 0;j < n;j++){
                    num1 += in.nextLong();
                }
                in.nextLine();
                long a = in.nextLong();
                long b = in.nextLong();
                long c = in.nextLong();
                long d = in.nextLong();
                in.nextLine();
                long num2 = Math.abs(c - a) + Math.abs(d - b);
                if(num1 >= num2 && ((num1 - num2) % 2 == 0)){
                    System.out.println("YES");
                }else{
                    System.out.println("NO");
                }
            }
        }
        in.close();
    }
}


发表于 2025-06-27 09:48:16 回复(2)