卡片游戏

    题意:

      Given is an ordered deck of n cards numbered 1to n with card 1 at the top and card n at thebottom.

The following operation is performed aslong as there are at least two cards in the deck:
             Throw away the top card and movethe card that is now on the top of thedeck to the bottom of the deck.Your task is to find the sequence of discardedcards and the last, remaining card.

 

输入每行包括一个n,输出每次扔掉的牌以及最后剩下的牌。样例输入如下:

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

 

思路分析:

        利用队列知识,用c.push(),c.front()跟c.pop()个函数,模拟题目的意思,把第一张卡片POP出去,但是要先输出第一张卡片,所以c.front()要在c.pop()前面,然后把第二张放到卡片堆底,直到最后一张。分两种情况,一是只有一张牌,一是至少两张牌。

源代码:

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 int main()
 5 {
 6 
 7     int n;
 8     while (cin >> n)
 9     {
10         if (n > 1 && n <= 50)
11         {
12             queue<int>a;                 
13             for (int i = 1; i <= n; i++)
14                 a.push(i);               //一堆卡片
15 
16             cout << "Discarded cards: ";
17 
18             while (a.size() >= 2)         //至少两张才可以进行这个卡片游戏  ,开始游戏
19             {
20                 if (a.size() == 2)         //刚好两张
21                 {
22                     cout << a.front();
23                     a.pop();
24                     break;
25                 }
26                 else
27                 {
28                     cout << a.front() << ", ";     
29                     a.pop();                 //扔掉第一张卡片
30                     a.push(a.front());       //把接下来的一张放在卡片堆底
31                     a.pop();                 //把接下来的一张扔掉
32                 }
33                 
34             }
35 
36             cout << endl;
37             cout << "Remaining card: " << a.front() << endl;
38 
39         }
40         else if (n == 1)                      //只有一张牌
41         {
42             cout << "Discarded cards:" << endl;
43             cout << "Remaining card: " << n << endl;
44 
45         }
46 
47         else
48             break;
49     }
50     return 0;
51 }

 

 

心得:

     第一次用队列的知识,队列是“先进先出”。解决这个题目,还是挺简单的(做出来了都简单,简直是废话=_=),但是一些输出格式还是要注意,分类的情况也要分清楚。模拟过程的时候,思路一定要清晰,可以自己在草稿纸上写写。就这样,干吧得~~~~~~~

 

posted @ 2015-07-24 20:17  白一  阅读(295)  评论(0编辑  收藏  举报