QOJ.ac

QOJ

Limite de temps : 10.0 s Limite de mémoire : 256 MB Points totaux : 100 Hackable ✓

#6994. 数据结构

Statistiques

在计算机科学中,2-3-4 树是一种自平衡搜索树,常用于实现字典。这里的数字表示每个拥有子节点的节点(内部节点)具有两个、三个或四个子节点。

2-节点与二叉树节点相同,包含一个数据元素,若为内部节点则有两个子节点。3-节点包含两个数据元素,若为内部节点则有三个子节点。4-节点包含三个数据元素,若为内部节点则有四个子节点。所有叶子节点都在同一深度,且所有数据保持有序。

下面介绍向 2-3-4 树插入值的过程。如果已插入的值不超过 2 个,则插入后的 2-3-4 树仅包含一个节点(根节点),其中包含若干数据元素。

否则,我们从 2-3-4 树的根节点开始执行以下过程:

  1. 如果当前节点是 4-节点:

    • 移除并保存中间值,得到一个 3-节点。
    • 将剩余的 3-节点拆分为一对 2-节点(缺失的中间值将在下一步处理)。
    • 如果这是根节点(因此没有父节点):
      • 中间值成为新的根 2-节点,树的高度增加 1。进入根节点(意味着当前节点变为新的根节点)。
    • 否则,将中间值向上推入父节点。进入父节点(意味着当前节点变为其父节点)。
  2. 如果当前节点是叶子节点,将值插入该节点并结束。

  3. 否则:

    • 找到区间包含待插入值的子节点。
    • 进入该子节点并重复步骤 1。

现在给定一棵初始为空的 2-3-4 树,依次插入 $n$ 个值 $a_1, a_2, \dots, a_n$。请编写程序,在插入所有给定值后,按先序遍历顺序打印 2-3-4 树。对于包含一个或多个数据元素的节点,程序应在一行中按升序打印这些数据元素。

输入格式

输入包含多个测试用例,第一行是一个正整数 $T$,表示测试用例的数量,最多为 50。

对于每个测试用例,第一行包含一个整数 $n$ ($1 \le n \le 5000$),表示将要插入 2-3-4 树的值的数量。第二行包含 $n$ 个整数 $a_1, a_2, \dots, a_n$。保证 $a_1, a_2, \dots, a_n$ 是 $1, 2, \dots, n$ 的一个排列。

输出格式

对于每个测试用例,首先输出一行 Case #x:,其中 $x$ 是从 1 开始的测试用例编号。接下来的若干行描述按先序遍历顺序的 2-3-4 树,每一行描述一个节点,包含该节点中的若干数据元素。

样例

输入格式 1

3
4
1 2 3 4
4
4 3 2 1
17
6 3 5 7 1 10 2 9 4 8 11 12 13 14 15 16 17

输出格式 1

Case #1:
2
1
3 4
Case #2:
3
1 2
4
Case #3:
5 9
2
1
3 4
7
6
8
11 13 15
10
12
14
16 17

说明

第一张图展示了第一个样例测试用例中第 4 次插入的过程。 第二张图展示了第三个测试用例最终的 2-3-4 树。

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.