Sample Input 1Copy
Copy
6 4 1 -1 5 3 2Sample Output 1Copy
Copy
3 5 4 1 2 6
If person 33, person 55, person 44, person 11, person 22, and person 66 stand in line in this order from front to back, the arrangement matches the given information.
Indeed, it can be seen that:
- person 11 is standing right behind person 44,
- person 22 is standing right behind person 11,
- person 33 is at the front of the line,
- person 44 is standing right behind person 55,
- person 55 is standing right behind person 33, and
- person 66 is standing right behind person 22.
Thus, print 33, 55, 44, 11, 22, and 66 in this order, separated by spaces.
Sample Input 2Copy
Copy
10 -1 1 2 3 4 5 6 7 8 9Sample Output 2Copy
Copy
1 2 3 4 5 6 7 8 9 10
Sample Input 3Copy
Copy
30 3 25 20 6 18 12 26 1 29 -1 21 17 23 9 8 30 10 15 22 27 4 13 5 11 16 24 28 2 19 7Sample Output 3Copy
Copy
10 17 12 6 4 21 11 24 26 7 30 16 25 2 28 27 20 3 1 8 15 18 5 23 13 22 19 29 9 14
#include<iostream>
using namespace std;
int main(){
int n,i,j,k=0;
cin>>n;
int b[n+1]={0};//创立数组放站队后结果
for(i=1;i<=n;i++){
cin>>j;
if(j==-1) k=i;//使名字是“-1”的站第一个,k是名字为“-1”的人序号;
else b[j]=i;//使得其他东西的名字成为数组序号,b[]是这东西的序号;
}
for(i=1;i<=n;i++){
cout<<k<<" ";//结果是先输出-1;然后
k=b[k];//寻找名字恰好是前一个人序号的使它的序号输出。
}
return 0;
}
是一个有点绕的东西,可以画图理解一下。