首页 > ACM题库 > HDU-杭电 > hdu 2319 Card Trick-模拟-[解题报告]C++
2014
01-05

hdu 2319 Card Trick-模拟-[解题报告]C++

Card Trick

问题描述 :

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

1.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.
2.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.
3.Three cards are moved one at a time…
4.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.

输出:

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.

样例输入:

2
4
5

样例输出:

2 1 4 3
3 1 4 5 2

题目链接:http://poj.org/problem?id=3032

题目大意:

给你一副牌(不大于13张且从A依次增加)。

第一次,将最上面的牌移动到最下面。

第二次,将最上面的牌移动到最下面,重复1次(共2次)

第三次,将最上面的牌移动到最下面,重复2次(共3次)

……

直到就剩1张牌。

保证出现的次序为A,2,3,4,5,6,7,8,9,10,J,Q,K

问初始时刻放置牌的顺序。

解题思路:

将最上面的放到最下面类似队列的经典操作。所以用队列模拟即可。

我用的双向队列,这样,反向模拟一次后队列中存放的就是这副牌的顺序(反着的),所以用双向队列deque从前向后输出即可。

代码如下:

#include<cstdio>
#include<cstring>
#include<deque>
#include<algorithm>
using namespace std;
int ac[110];
deque<int>q; //双向队列模拟

int main()
{
	int ncase, n;
	scanf("%d", &ncase);
	while(ncase--)
	{
		scanf("%d", &n);
		q.push_back(n);
		for(int i = n - 1; i >= 1; --i)
		{
			q.push_back(i);
			for(int j = 1; j <= i; ++j)
			{
				int temp = q.front();
				q.push_back(temp);
				q.pop_front();
			}
		}
		while(!q.empty())
		{
			printf("%d ", q.back());
			q.pop_back();
		}
		printf("\n");
	}
	return 0;
}

解题转自:http://blog.csdn.net/niushuai666/article/details/7454249


  1. 站长,你好!
    你创办的的网站非常好,为我们学习算法练习编程提供了一个很好的平台,我想给你提个小建议,就是要能把每道题目的难度标出来就好了,这样我们学习起来会有一个循序渐进的过程!

  2. 算法是程序的灵魂,算法分简单和复杂,如果不搞大数据类,程序员了解一下简单点的算法也是可以的,但是会算法的一定要会编程才行,程序员不一定要会算法,利于自己项目需要的可以简单了解。