解题思路 这道题要求我们根据每个小朋友后面的人的编号,重构整个队伍的顺序。关键在于理解每个小朋友的位置关系,并按照从队首到队尾的顺序输出。 方法思路 输入处理:读取每个小朋友后面的人的编号,并存储在一个数组中。 遍历队伍:从队首开始,根据每个小朋友后面的人的编号,依次找到下一个小朋友,直到队尾(后面的编号为 0)。
#include <bits/stdc++.h> using namespace std;
const int MAXN = 1e6 + 5; int next_child[MAXN]; // next_child[i] 表示编号为i的小朋友后面的人的编号
int main() { int n; cin >> n;
// 读取每个小朋友后面的人的编号
for (int i = 1; i <= n; i++) {
cin >> next_child[i];
}
int current;
cin >> current; // 读取队首小朋友的编号
// 输出队首小朋友
cout << current;
// 依次输出后续小朋友,直到队尾(后面的编号为0)
while (next_child[current] != 0) {
current = next_child[current];
cout << " " << current;
}
cout << endl;
return 0;
}
代码解释 输入处理:使用数组 next_child 存储每个小朋友后面的人的编号。 遍历队伍:从队首开始,根据 next_child 数组依次找到下一个小朋友,并输出其编号,直到遇到队尾(后面的编号为 0)。