算法习题---5-3卡牌游戏(UVa10935)
一:题目
给定n张卡片,按照1-n的顺序编号,然后拿出一张卡片扔掉,拿出一张卡片放到最后,重复该操作直到只剩1张卡片。
求扔掉的卡片序列和最后剩的卡片的编号。
(一)样例输入
7 //卡牌编号从1到7 19 //卡牌编号从1到19 10 6 0
(二)样例输出
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
二:代码实现
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <queue> using namespace std; #define MAX_N 15 int main103() { freopen("data5_3_h.in", "r", stdin); freopen("data5_3_h.out", "w", stdout); int num,first_ele; while (cin>>num&&num!=0) { queue<int> card; //使用队列进行模拟 bool flag = false; for (int i = 1; i <= num; i++) card.push(i); cout << "Discarded cards: "; while (card.size()!=1) { if (!flag) { cout << card.front(); if (card.size() != 2) cout << ", "; } else card.push(card.front()); card.pop(); flag = !flag; } cout << "\nRemaining card:" << card.front() << endl; } freopen("CON", "r", stdin); freopen("CON", "w", stdout); return 0; }