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

  • Post author:
  • Post category:其他


UVa10935


Throwing cards away I

有一堆卡片,从顶到底依次写着

1



n

,要对卡片做如下操作:将顶部第

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
*/



版权声明:本文为RayoNicks原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。