0%

# 题目2 : Tree Restoration

## 描述

There is a tree of N nodes which are numbered from 1 to N. Unfortunately, its edges are missing so we don’t know how the nodes are connected. Instead we know:

1. Which nodes are leaves

2. The distance (number of edges) between any pair of leaves

3. The depth of every node (the root’s depth is 1)

4. For the nodes on the same level, their order from left to right

Can you restore the tree’s edges with these information? Note if node u is on the left of node v, u’s parent should not be on the right of v’s parent. ## 输入

The first line contains three integers N, M and K. N is the number of nodes. M is the depth of the tree. K is the number of leaves.

The second line contains M integers A1, A2, … AM. Ai represents the number of nodes of depth i.

Then M lines follow. The ith of the M lines contains Ai numbers which are the nodes of depth i from left to right.

The (M+3)-th line contains K numbers L1, L2, … LK, indicating the leaves.

Then a K × K matrix D follows. Dij represents the distance between Li and Lj.

1 ≤ N ≤ 100

## 输出

For every node from 1 to N output its parent. Output 0 for the root’s parent.

# 解析

• 对于每层第一个节点，上一层的第一个非叶子节点必然是这个节点的父节点。
• 此时记录该节点的父节点，并把父节点的子节点记录为当前节点，并以此更新这个父节点与其他已知节点的距离。
• 然后看该层下一个节点。
• 下一个节点若与前一个节点距离为2，则两者父节点相同。
• 若大于2，则该节点的父节点是上一层的下一个非叶子节点。同时记录父、子节点，更新距离。
• 如此每层循环，每层结束进入上一层，直到第二层。（第一层根节点不必再判断了。

## WA代码（C++）：

100个节点的数据太多了。暂时无法测试。

## 最终结果

1490 Tree Restoration AC G++ 5ms 0MB