POJ-3032 Card Trick

来源:互联网 发布:mac打字不显示候选框 编辑:程序博客网 时间:2024/05/17 12:24

POJ-3032(HZNU-1128): Card Trick


                                        时间限制: 1 Sec  内存限制: 64 MB

题目描述
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.
这里写图片描述
输入
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.

输出
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…

样例输入
2
4
5
样例输出
2 1 4 3
3 1 4 5 2

题目思路:逆序思维,用队列存放入最大值n,翻转(即把首元素扔到最后)n次,再存入n-1,翻转n-1次…..依次执行。最后逆序输出
例如:n = 4时,1.先存入4,翻转4次后是4;
2.存入3,翻转3次后是4 3;
3.存入2,翻转2次后是4 3 2;
4.存入1,翻转1次后是2 1 4 3;

以下是代码:

#include <vector>#include <map>#include <set>#include <algorithm>#include <iostream>#include <cstdio>#include <cmath>#include <cstdlib>#include <string>#include <cstring>#include <queue>using namespace std;int main(){    int t;    cin >> t;    while(t--)    {        int n;        cin >> n;        int nn = n;        int cnt;        queue <int> q;        while(n > 0)        {            q.push(n);            cnt = n--;            while(cnt--)            {                int temp = q.front();                q.pop();                q.push(temp);            }        }        int first = 1;        int a[100] = {0};        for (int i = 0; i < nn; i++)        {            a[i] = q.front();            q.pop();        }        cout << a[nn - 1];        for (int i = nn - 2; i >= 0; i--)        {            cout << " " << a[i];        }        cout << endl;     }     return 0;}
0 0
原创粉丝点击