CCC 2017 J3 Exactly Electrical Solution: Manhattan Distance and Parity



☰

开始北极星测评

CP 每周编程挑战

CCC 2017 J3 Exactly Electrical Solution: Manhattan Distance and Parity

Use Manhattan distance and parity to decide whether the car can reach its destination while using exactly all available charge.

竞赛编程每周挑战

CCC 2017 J3 Exactly Electrical 题解:曼哈顿距离为什么还要检查奇偶性?

用曼哈顿距离和奇偶性,判断汽车能否在到达终点时恰好用完全部电量。

分享这篇文章

复制链接、使用手机分享、用微信扫码,或通过邮件发送。




邮箱

Having enough battery to reach the destination is not the same as using exactly all the battery. CCC 2017 J3 Exactly Electrical is a compact lesson in turning one word in the statement into a second algorithmic condition: check both Manhattan distance and parity.

本题在 CCC 数据结构与算法路线图中的位置

  • Level: CCC Junior J3; an entry point to proof-based reasoning
  • Pattern: Manhattan Distance + Parity + Necessary and Sufficient Conditions
  • 前置知识:abs(), conditionals, modulo %, Cartesian coordinates
  • What this teaches: separate the minimum amount of work from whether an exact amount is achievable
  • Where it appears again: shortest paths on grids, checkerboard parity, invariants, reachability tests, and edge-case design

What to Study Next

What the Problem Is Asking

Grid City is an infinite integer grid. Each move to an adjacent intersection, north, south, east, or west, uses one unit of charge. The input gives a start (a,b), a destination (c,d), and charge t. Output Y exactly when the car can arrive at the destination with an empty battery.

The car may turn around and revisit intersections. Those details matter because they allow two-step detours.

Where Beginners Often Get Stuck

Checking only distance <= t proves that the battery is large enough for a shortest path. It does not prove that every extra unit can be spent. From (0,0) to (1,0), the shortest distance is 1. With t=2, one move reaches the destination but one unit remains. Leaving and returning would require two more moves, so the correct output is N.

Core Algorithm Idea

The shortest number of moves is the Manhattan distance:

distance = |a - c| + |b - d|

If t < distance, the trip is impossible. If the shortest path leaves an even number of extra moves, every pair can be spent by moving to a neighbouring intersection and back. An odd leftover cannot be removed by such round trips.

Therefore:

possible exactly when
t >= distance and (t - distance) % 2 == 0

For the shared example from (0,0) to (2,1), the distance is 3. Charge 3 works, charge 4 fails because one move remains, and charge 5 works because the two extra moves form one round trip.

Python 解法

a, b = map(int, input().split())
c, d = map(int, input().split())
t = int(input())

distance = abs(a - c) + abs(b - d)
extra = t - distance

if extra >= 0 and extra % 2 == 0:
    print("Y")
else:
    print("N")

C++ 解法

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
    int a, b, c, d, t;
    cin >> a >> b >> c >> d >> t;

    int distance = abs(a - c) + abs(b - d);
    int extra = t - distance;

    cout << (extra >= 0 && extra % 2 == 0 ? "Y\n" : "N\n");
    return 0;
}

Why the Algorithm Is Correct

Any route must make at least |a-c| net horizontal moves and |b-d| net vertical moves, so t >= distance is necessary. Every move flips the parity of x+y, so a route ending at the destination must have the same parity as the Manhattan distance; therefore the leftover must be even.

Conversely, take a shortest route. If the leftover is a non-negative even number, split it into pairs. Spend each pair by moving to any neighbouring intersection and immediately returning. The grid is infinite and revisits are allowed, so this construction always works. The two tests are therefore both necessary and sufficient.

复杂度分析

  • Time: O(1)
  • Extra space: O(1)

The algorithm performs a fixed number of arithmetic and logical operations, independent of the coordinate values.

常见错误

  1. Checking distance but not parity.
  2. Using Euclidean distance instead of Manhattan distance.
  3. Checking whether t itself is even instead of comparing its parity with the distance.
  4. Mishandling zero charge when the start equals the destination.
  5. Simulating paths or using BFS on an obstacle-free infinite grid.

Review Questions

  1. What is the distance from (1,1) to (4,3)? Does t=7 work?
  2. Why can two extra moves always be spent, while one cannot?
  3. If the start equals the destination, which values of t work?
  4. Would the same proof remain sufficient if the grid contained blocked intersections?
  5. Create one test that fails the distance condition and another that fails only the parity condition.

从起点开到终点,电量必须刚好用完。只要电量不少于最短距离,就一定能到吗?CCC 2017 J3 Exactly Electrical 的关键陷阱正藏在“刚好”两个字里:除了距离够不够,还必须检查多出来的步数是不是偶数。

本题在 CCC DSA 地图里的位置

  • Level: CCC Junior J3,Junior 到算法证明的入门题
  • Pattern: Manhattan Distance + Parity + Necessary and Sufficient Conditions
  • 前置知识:abs()、条件判断、取模 %、二维坐标
  • What this teaches: 把“至少需要多少步”和“能否刚好走这么多步”拆成两个独立条件
  • Where it appears again: 网格最短路、棋盘颜色/奇偶性不变量、状态可达性判断、边界测试

下一步推荐

如果你已经理解这道题,可以继续看:

题目要我们做什么

Grid City 的街道和大道形成一个无限整数网格。汽车每向上、下、左或右移动一个街区,就消耗一单位电量。输入给出:

  1. 起点 (a,b);
  2. 终点 (c,d);
  3. 初始电量 t。

汽车可以掉头,也可以重复经过同一个路口。我们要判断:能否在到达终点时恰好把 t 单位电量全部用完?可以输出 Y,否则输出 N。

初学者容易卡在哪里

最常见的错误是只写:

if distance <= t:
    print("Y")

这个条件只说明电量足够走一条最短路线,却没有保证剩余电量能被合法消耗。

例如从 (0,0) 到 (1,0),最短距离是 1。如果有 2 单位电量,走一步已经到终点,但还剩 1 步。任何额外移动都会离开终点;再走回来又要第二步。因此答案是 N,不是 Y。

核心算法概念一:曼哈顿距离

在只能上下左右移动的网格里,从 (a,b) 到 (c,d) 至少需要:

distance = |a - c| + |b - d|

横坐标差表示至少要走多少次东西方向,纵坐标差表示至少要走多少次南北方向。两者相加,就是 Manhattan distance。

如果 t < distance,电量连最短路线都不够,答案一定是 N。

核心算法概念二:为什么要检查奇偶性

如果走完最短路线后还有电量,我们可以用“走出去一步,再走回来一步”的方式消耗 2 单位电量:

当前位置 -> 相邻路口 -> 原位置

因此,任何非负偶数剩余量都能消耗;奇数剩余量却无法只靠这种往返动作消耗干净。

所以完整判定是:

t >= distance
并且
(t - distance) % 2 == 0

也可以直接检查 t 与 distance 同奇偶,但写成“剩余量为非负偶数”更贴近题意。

这两个条件为什么缺一不可

设 extra = t - distance。

情况 distance t extra 结论
电量不足 3 2 -1 N
刚好最短距离 3 3 0 Y
多一单位 3 4 1 N
多两单位 3 5 2 Y

从 (0,0) 到 (2,1) 的最短距离是 3:

  • t=3:走东、东、北,刚好到达;
  • t=4:剩 1 步,无法消耗;
  • t=5:先走最短路线,再加一次往返,刚好用完。

这张表很适合当作提交前的 edge-case checklist。

Python 解法

a, b = map(int, input().split())
c, d = map(int, input().split())
t = int(input())

distance = abs(a - c) + abs(b - d)
extra = t - distance

if extra >= 0 and extra % 2 == 0:
    print("Y")
else:
    print("N")

代码只有两个判断:剩余电量不能为负,并且必须为偶数。不要模拟汽车逐步移动,也不需要 BFS,因为网格没有障碍,公式已经完整描述了可达条件。

C++ 解法

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
    int a, b, c, d, t;
    cin >> a >> b;
    cin >> c >> d;
    cin >> t;

    int distance = abs(a - c) + abs(b - d);
    int extra = t - distance;

    if (extra >= 0 && extra % 2 == 0) {
        cout << "Y\n";
    } else {
        cout << "N\n";
    }

    return 0;
}

Python 和 C++ 使用完全相同的模型。语言不同,算法不变。

正确性说明

要证明判定正确,需要分别证明“必要”和“充分”。

必要性:

  • 任何路线都必须完成至少 |a-c| 次横向净移动和 |b-d| 次纵向净移动,所以 t 必须不少于 Manhattan distance。
  • 每一步都会改变 (x+y) 的奇偶性。经过 t 步后能否落在终点,要求 t 与起终点的 Manhattan distance 同奇偶,因此 t-distance 必须是偶数。

充分性:

  • 先沿任意一条最短路线走 distance 步到达终点。
  • 如果剩余 t-distance 是非负偶数,就把它分成若干对;每一对用“到相邻路口再返回”消耗。
  • 因为网格无限、允许掉头和重复访问,这些往返动作总能完成。

因此,两个条件同时成立时一定存在合法路线;任何一个不成立时都不可能存在。

复杂度分析

  • 时间复杂度:O(1)
  • 额外空间复杂度:O(1)

无论坐标和电量多大,程序都只执行固定次数的减法、绝对值、加法和取模。这里的 Big O 不是说程序“一步完成”,而是输入数值变大时,操作次数不会随之增长。

常见错误

  1. 只检查 distance <= t,忘记奇偶性。
  2. 用欧几里得距离或平方根;网格只能上下左右走,应使用 Manhattan distance。
  3. 把条件写成 t % 2 == 0;真正要比较的是 t 和 distance 的奇偶性。
  4. 忘记 t=0:起点等于终点时输出 Y,否则输出 N。
  5. 用 BFS 或逐步模拟,把一个 O(1) 判定写成复杂搜索。

复习问题

  1. 从 (1,1) 到 (4,3) 的 Manhattan distance 是多少?若 t=7,答案是什么?
  2. 为什么“多出来 2 步”总能消耗,而“多出来 1 步”不行?
  3. 起点等于终点时,哪些 t 会输出 Y?
  4. 如果网格中出现障碍物,这个公式还足够吗?为什么?
  5. 你能分别写出一个只通过距离检查、一个只通过奇偶检查但最终答案为 N 的测试吗?

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

Back to CP Weekly Challenge
返回竞赛编程每周挑战

CP ACADEMY

不确定哪些挑战适合你?

通过 CP 测评了解当前起点,选择下一步练习主题。你也可以直接阅读和练习,无需先完成测评。

60 分钟连续作答 · Python 或 C++ · 选择目标比赛

了解我的 CP 水平

滚动至顶部