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:
Which nodes are leaves
The distance (number of edges) between any pair of leaves
The depth of every node (the root’s depth is 1)
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.
int main() { int N, M, K; //N is the number of nodes. M is the depth of the tree. K is the number of leaves. cin >> N >> M >> K;
int depth[105] = { 0 }; //depth[] represents the number of nodes of depth[i]. for (int i = 0; i < M; i++) { cin >> depth[i]; }
int tree[105][105] = { 0 }; //the nodes of depth[i] from left to right. for (int i = 0; i < M; i++) { for (int j = 0; j < depth[i]; j++) { cin >> tree[i][j]; } }
int leaves[105] = { 0 }; //leaves node int is_leaves[105] = { 0 }; //Determine whether a node is a leaf node for (int i = 0; i < K; i++) { cin >> leaves[i]; is_leaves[leaves[i]] = 1; }
int dis[105][105] = { 0 }; // the distance between Li and Lj. for (int i = 0; i < K; i++) { for (int j = 0; j < K; j++) { cin >> dis[leaves[i]][leaves[j]]; } }
int father[105] = { 0 }; //answer int son[105] = { 0 }; //record a child node of a node
father[tree[0][0]] = 0; for (int i = 0; i < depth[1]; i++) { father[tree[1][i]] = tree[0][0]; }
for (int i = M - 1; i >= 2; i--) { int up_point = 0; ////i-1层中第一个不是叶子节点的节点,必定是当前节点的父亲 while (is_leaves[tree[i - 1][up_point]] && up_point < depth[i - 1]) { up_point++; } int point_a = tree[i][0]; father[point_a] = tree[i - 1][up_point]; son[tree[i - 1][up_point]] = point_a; //更新距离 for (int k = 0; k < N; k++) { if (dis[point_a][k] > 0) { dis[father[point_a]][k] = dis[k][father[point_a]] = dis[point_a][k] - 1; } }
for (int k = 0; k < K; k++) { dis[leaves[k]][father[point_a]] = dis[father[point_a]][leaves[k]] = dis[leaves[k]][point_a] - 1; }