10935 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
解题思路:我们首先输入一个x,来确定我们需要给定的牌数和我们的牌的上面的数字。然后我们将我们每次输入的数都用push_back()存到一个set容器中
(建立一个set容器,需要我们用到<map>这个头文件)我们在我们的牌还剩大于1时才进行扔牌的操作。用front()函数将第一个数输出来,再把pop()函数删除第一个数,用front()函数将第一个数取出,再用push()函数把它插入到容器的后面,同时用pop函数删除这个数。最后我们要将容器中剩下的那个数据清除掉。(我们要注意我们的输出形式)
#include <iostream> #include <queue> using namespace std; queue<int>v; int main() { int x; while(cin>>x&&x) { for(int i=0;i<x;i++) v.push(i+1); cout<<"Discarded cards:"; while(v.size()>1) { if(v.size()>2) cout<<" "<<v.front()<<","; else cout<<" "<<v.front(); v.pop(); v.push(v.front()); v.pop(); } cout<<endl; cout<<"Remaining card:"<<" "<<v.front()<<endl; v.pop(); } return 0; }程序代码: