Time Limit: 3000MS | Memory Limit: Unknown | 64bit IO Format: %lld & %llu |
Description
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.
Each line of input (except the last) contains a number n ≤ 50. The last line contains 0 and this line should not be processed. 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
Output for sample input
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
解题报告:
大意是给出n张牌,例如1 2 3 4 5.进行以下操作:<1>将第一张牌丢弃
<2>将第二张牌放在整副牌末尾
<3>goto <1>直到剩下最后一张牌
可以使用队列的结构,但是这题要注意输出格式逗号+空格以及n=1的情况时没有丢弃的牌,此时Discarded cards:后面自然不含空格。
参考代码:
#include <iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
queue<int> q;
int main()
{
//freopen("in.txt","r",stdin);
int n,a[51],t;
while(cin>>n&&n>0)
{
for(int i=0;i<n;i++)
{
//压入队列
q.push(i+1);
}
t=0;
while(!q.empty())
{
//cout<<q.front()<<" ";//取出队列头部
a[t++]=q.front();
q.pop();//头部出列
q.push(q.front());//头部压入队列末尾
q.pop();//已经压入队尾的队列弹出
}
cout<<"Discarded cards:";
if(t!=1)
cout<<" ";
for(int i=0;i<t-1;i++)
{
if(i!=0)
cout<<", ";
cout<<a[i];
}
cout<<endl;
cout<<"Remaining card: "<<a[t-1]<<endl;
//}
}
return 0;
}