UVA

/*
  这题用到了队列的思想
  
  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;
}


原文地址:https://www.cnblogs.com/mofushaohua/p/7789431.html