利用队列解密QQ号码(三种方法)-->改编自《啊哈!算法》

【问题描述】
新学期开始了,小哈是小哼的新同桌。小哼向小哈询问 QQ号,小哈当然不会直接告诉小哼啦,原因嘛你懂的。所以小哈给了小哼一串加密过的数字,同时小哈也告诉了小哼解密规则。规则是这样的:首先将第 1个数删除,紧接着将第2个数放到这串数的末尾,再将第3个数删除并将第4个数放到这串数的末尾,再将第5个数删除……直到剩下后一个数,将后一个数也删除。按照刚才删除的顺序,把这些删除的数连在一起就是小哈的QQ啦。现在你来帮帮小哼吧。小哈给小哼加密过的一串数是“6 3 1 7 5 8 9 2 4”。

 
【算法代码一】

#include<bits/stdc++.h>
using namespace std;

int a[100];
int main() {
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	
	int head=1;
	int tail=n+1;
	while(head<tail) {
		cout<<a[head]<<" ";
		head++;
		
		a[tail]=a[head];
		tail++;
		
		head++;
	}

	return 0;
}

/*
input:
9
6 3 1 7 5 8 9 2 4

output:
6 1 5 9 4 7 2 8 3
*/

【算法代码二:利用结构体】

#include <bits/stdc++.h>
using namespace std;

struct duilie{
	int data[100];
	int head;
	int tail;
};

int main() {
	int n;
	cin>>n;
	
	duilie q;	
	q.head=1;
	q.tail=1;
	
	for(int i=1; i<=n; i++) {
		cin>>q.data[q.tail];
		q.tail++;
	}

	while(q.head<q.tail) {		
		cout<<q.data[q.head]<<" ";
		q.head++;

		q.data[q.tail]=q.data[q.head];
		q.tail++;
		
		q.head++;
	}

	return 0;
}

/*
input:
9
6 3 1 7 5 8 9 2 4

output:
6 1 5 9 4 7 2 8 3
*/


【算法代码三:利用STL】

#include<bits/stdc++.h>
using namespace std;

int main() {
	int a;
	int n;
	cin>>n;	
	queue<int> s;
	
	for(int i=0; i<n; i++) {
		cin>>a;
		s.push(a);
	}
	
	while(s.empty()!=1) {
		cout<<s.front()<<" ";
		s.pop();
		s.push(s.front());
		s.pop();
	}

	return 0;
}

/*
input:
9
6 3 1 7 5 8 9 2 4

output:
6 1 5 9 4 7 2 8 3
*/

【参考文献】
https://www.ituring.com.cn/book/tupubarticle/29874

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值