卡片游戏(UVa 10935)

Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at the bottom. The following operation is performed as long as there are at least two cards in the deck:

Throw away the top card and move the card that is now on the top of the deck to the bottom of the deck.

Your task is to find the sequence of discarded cards and the last, remaining card.

Input

Each line of input (except the last) contains a number n ≤ 50. The last line contains ‘0’ and this line should not be processed.

Output

For each number from the input produce two lines of output. The first line presents the sequence of discarded cards, the second line reports the last remaining card. No line will have leading or trailing spaces. See the sample for the expected format.

Sample Input

7

19

10

6

0

Sample Output

Discarded cards: 1, 3, 5, 7, 4, 2

Remaining card: 6

Discarded cards: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 4, 8, 12, 16, 2, 10, 18, 14

Remaining card: 6

Discarded cards: 1, 3, 5, 7, 9, 2, 6, 10, 8

Remaining card: 4

Discarded cards: 1, 3, 5, 2, 6

Remaining card: 4

思路:此题需要去除和移动卡片位置,如果操作后重新排序,那步骤将极为繁琐,所以直接定义更大的数组容量,将移动的卡片直接放在后面,便于操作和输出。本题还有比较复杂的一点就是最后一位输出后面没有逗号,我在编写过程中利用做标记的方法达到效果(详情见代码),特别注意数字前还有一个空格不要忘记输出。

以下是详细代码:

#include<iostream>
using namespace std;
int main()
{
	int n,i,a[110];
	while(cin>>n && n)
	{
		for(i=1;i<=n;i++)
			a[i]=i;
		cout<<"Discarded cards:";
		int h=1,t=n;
		for(i=1;i<n;i++)
		{
			if(h<t)
			{
				cout<<" "<<a[h];
				h++;
			}
			if(h<t)
			{
				cout<<",";
				t++;
				a[t]=a[h];
				h++;
			}
		}	
		cout<<"\n";
		cout<<"Remaining card: "<<a[t]<<endl;
	}
}

未经授权请勿转载,违者必究!

猜你喜欢

转载自blog.csdn.net/weixin_41618712/article/details/81226494
今日推荐