返回学习页
知识点指南

Sorting

Sorting changes raw input order into useful order. It often makes equal values adjacent, reveals gaps, or prepares the data for a greedy decision.

什么时候使用

读题时可以留意这些信号。

  • Original order is not important, or positions can be stored separately.
  • The task asks about groups, gaps, closest/farthest values, or ordered choices.
  • A later scan only makes sense after arranging values.

常见错误

提交前可以检查这些小陷阱。

  • Sorting when original order is essential.
  • Sorting by the wrong key.
  • Comparing adjacent values before sorting.

怎么写成代码

把知识点翻译成变量、循环、判断和更新。

  • Read the values into an array/list.
  • Sort before scanning or making choices.
  • Compare adjacent sorted values to find gaps or groups.
  • Store original indices if the original position is still needed.

在 Block 题里长什么样

答题时通常会看到这些步骤被拆成代码块。

  1. 1Read N and values.
  2. 2Sort values.
  3. 3Initialise answer/group count/best gap.
  4. 4Loop through sorted neighbours.
  5. 5Update answer based on adjacent relation.
  6. 6Print result.

题目里怎么出现

读题时先找这些信号,再决定答案区应该选哪些 blocks。

  • The statement says order does not matter, or asks for groups by closeness.
  • The raw input order is described as arbitrary.
  • Neighbouring after sorting has a story meaning.

Count groups after sorting

一个小型模板,展示代码和 blocks 的对应关系。

C++

sort(values.begin(), values.end());
int groups = 1;
for (int i = 1; i < N; i++) {
    if (values[i] - values[i - 1] > K) groups++;
}
cout << groups << '\n';

Python

values.sort()
groups = 1
for i in range(1, N):
    if values[i] - values[i - 1] > K:
        groups += 1
print(groups)

对应 block 顺序

  1. 1Read values.
  2. 2Sort values.
  3. 3Start with one group.
  4. 4Loop through adjacent sorted values.
  5. 5Start a new group when the gap is too large.
  6. 6Output group count.

建议先练这道题

可以先从 Shopping Spree 开始,再回到这里复盘知识点信号。

打开题目