AtCoder Beginner Contest 337(1)

该代码片段展示了如何使用C++编程解决站队问题,给定一个包含整数和-1的序列,-1表示站在第一位,程序输出从-1开始的站队顺序。通过遍历和引用数组元素找到正确的位置。
摘要由CSDN通过智能技术生成

 

Sample Input 1Copy

Copy

6
4 1 -1 5 3 2

Sample 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 9

Sample 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 7

Sample 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;
}

 

是一个有点绕的东西,可以画图理解一下。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值