首页 > 代码库 > 紫书第五章训练3 D - Throwing cards away I

紫书第五章训练3 D - Throwing cards away I

D - Throwing cards away I

 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

喜欢斗地主的你赶紧来洗牌啦,你有n张牌,先把第一张扔掉,然后把第一张放在最后,然后再把第一张牌扔掉,剩一张牌时再输出你扔掉的这张牌。本来想到要用数组模拟,类似于约瑟夫环。但是GG,自己试了几组并不对,然后自己就被晾在那了,改了很久的数组突然发现很多人AC了,我就想也许数组比较麻烦,我需要抖机灵想些别的数据结构,一拍大腿这就是队列啊,哭晕在厕所。哎,这种典型的队列和括号匹配所代表的栈自己得十分熟悉才行啊,自动hash匹配啊。有种回到高考的感觉,但是高考我可没这么努力啊。

技术分享
#include<iostream>
using namespace std;
int s[100];
int n;
int main()
{

    while(cin>>n&&n)

    {

        int k=1;
        int l=n;
        for(int i=1; i<=n; i++)s[i]=i;
        if(n==1)
        cout<<"Discarded cards:"<<endl<<"Remaining card: 1"<<endl;
        else
        {
            cout<<"Discarded cards: ";
            while(k<l)
            {
                cout<<s[k];
                k++;
                if(k<l)
                cout<<", ";
                if(k==l)
                cout<<endl<<"Remaining card: "<<s[k]<<endl;
                s[++l]=s[k];
                k++;
            }
        }
    }
return 0;
}
View Code

 

紫书第五章训练3 D - Throwing cards away I