/*
这题用到了队列的思想
BTW,查题解时,看到两个大佬的代码真是简洁,于是果断抛弃了自己写的,用他们的思路重新做了一遍
参考博客:
http://www.cnblogs.com/AlgoWing/archive/2013/03/04/3189616.html
http://blog.csdn.net/mobius_strip/article/details/45157587
另附C++中对于队列的讲解blog:
http://www.cnblogs.com/xuning/p/3321733.html
(注意,队列的size的返回值并不是int型,所以使用前应先强制转换,老生常谈了...)
*/
//法一:
#include <iostream>
using namespace std;
const int maxn = 100000;
int Q[maxn];
int main()
{
int n;
while (cin >> n && n)
{
for (int i = 1; i <= n; i++) Q[i] = i;
int head = 1, tail = n, first = 1;
cout << "Discarded cards:"; //注意冒号后无空行
while (head < tail)
{
if (!first) cout << ",";
cout << " " << Q[head];
head++;
Q[++tail] = Q[head++];
first = 0; //除了第一次不用输出逗号,其他时候都要
}
cout << endl << "Remaining card: " << Q[head] << endl;
}
return 0;
}
//法二:
#include <iostream>
#include <queue>
using namespace std;
queue<int> Q;
int n;
int main()
{
while (cin >> n && n)
{
for (int i = 1; i <= n; i++) Q.push(i);
cout << "Discarded cards:";
while ((int)Q.size() > 1)
{
if ((int)Q.size() > 2)
{
cout << " " << Q.front() << ",";
Q.pop();
Q.push(Q.front());
Q.pop();
}
else
{
cout << " " << Q.front();
Q.pop();
}
}
cout << endl << "Remaining card: " << Q.front() << endl;
Q.pop();
}
return 0;
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步