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

被折叠的 条评论
为什么被折叠?



