算法竞赛入门经典 习题5-3

该博客介绍了一种使用C++和双端队列(deque)解决编程挑战的方法,具体是关于如何处理一堆卡片,从顶部开始按特定规则丢弃和重新排列卡片,直到只剩一张。当输入为1时,程序会进行特殊处理。博主通过示例代码展示了如何实现这一过程,并附带了测试用例。

UVa10935

Throwing cards away I

有一堆卡片,从顶到底依次写着1n,要对卡片做如下操作:将顶部第1张卡片扔掉,并将第2张卡片放到最底部,直到只剩下最后一张卡片,依次输出扔掉的卡片和最后剩下的卡片。

根据题意使用双端队列deque模拟即可,注意单独处理输入为1的情况。

#include <iostream>
#include <deque>

using namespace std;

int main()
{
	int n = 0;
	while (cin >> n) {
		if (n == 0) break;
		else if (n == 1) {
			cout << "Discarded cards:\n" << "Remaining card: 1" << endl;
			continue;
		}
		else {
			deque<int> cards;
			for (int i = 1; i <= n; i++)
			{
				cards.push_back(i);
			}
			cout << "Discarded cards: ";
			while (cards.size() > 2) {
				cout << cards.front() << ", ";
				cards.pop_front();
				cards.push_back(cards.front());
				cards.pop_front();
			}
			cout << cards.front() << endl;
			cout << "Remaining card: " << cards.back() << endl;
		}
	}
	return 0;
}
/*
7
19
10
6
0
1 2 3 4 5 6
3 4 5 6 2
5 6 2 4
2 4 6
6 4
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值