天天看點

POJ 3032 Card Trick 紙牌順序

原題 http://poj.org/problem?id=3032

題目:

Card Trick

Time Limit: 1000MS Memory Limit: 65536K

Total Submissions: 4013 Accepted: 2874

Description

The magician shuffles a small pack of cards, holds it face down and performs the following procedure:

The top card is moved to the bottom of the pack. The new top card is dealt face up onto the table. It is the Ace of Spades.

Two cards are moved one at a time from the top to the bottom. The next card is dealt face up onto the table. It is the Two of Spades.

Three cards are moved one at a time…

This goes on until the nth and last card turns out to be the n of Spades.

This impressive trick works if the magician knows how to arrange the cards beforehand (and knows how to give a false shuffle). Your program has to determine the initial order of the cards for a given number of cards, 1 ≤ n ≤ 13.

Input

On the first line of the input is a single positive integer, telling the number of test cases to follow. Each case consists of one line containing the integer n.

Output

For each test case, output a line with the correct permutation of the values 1 to n, space separated. The first number showing the top card of the pack, etc…

Sample Input

2

4

5

Sample Output

2 1 4 3

3 1 4 5 2

思路:

對于一堆牌,滿足條件:第一次移動最頂上的一張到最底下後,面上的是A。拿走A。

第二次移動最頂上的兩張到最底下後,面上的是2。拿走2。

以此類推,當移動n次後剩下的就隻剩一張n了。再拿走n。

遊戲結束。

注意:假如要移動5張,隻剩下4張,因為先移動4次後會變成原來的樣子,是以隻需要移動5%4次。

而我們需要做的就是求出滿足要求的這堆牌。

是以這是一道需要用到隊列的模拟題。反向模拟就可以求出答案。

代碼:

#include <iostream>
#include"string.h"
#include"cstdio"
#include"stdlib.h"
#include"algorithm"
#include"queue"
#include"stack"
using namespace std;
typedef long long int lint;


int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        queue <int> q;
        int n;
        scanf("%d",&n);
        for(int i=n;i>;i--)
        {
            q.push(i);
            for(int j=;j<i;j++)
            {
                int tem=q.front();
                q.pop();
                q.push(tem);
            }
        }
        stack <int> s;
        while(!q.empty())
        {
            s.push(q.front());
            q.pop();
        }
        while(!s.empty())
        {
            printf("%d",s.top());
            s.pop();
            if(!s.empty())  printf(" ");
        }
        printf("\n");
    }
    return ;
}
           

由于本題的n的取值為1到13,是以我們也可以手動算出所有的結果,暴力枚舉求解。