題目: UVa - 10935 - Throwing cards away I
題目說明
每筆測資為一個數字 n,會有一個 1 ~ n 的紙牌堆,題目要求丟掉最上面的牌,然後把目前最上面的那張牌放到牌堆的最下面。
解題思路
利用 queue 先進先出的特性,先輸出 front()
然後 pop()
掉,再把 front()
push()
進去,最後再 pop()
即可。
參考解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| #include <iostream> #include <queue>
using namespace std;
int main() { int n; queue< int > cards;
while ((cin >> n) && n != 0) { for (int i = 1; i <= n; ++i) cards.push(i);
if (cards.size() == 1) cout << "Discarded cards:" << endl << "Remaining card: " << cards.front() << endl; else { cout << "Discarded cards: "; while (cards.size() > 2) { cout << cards.front() << ", "; cards.pop(); cards.push(cards.front()); cards.pop(); } cout << cards.front(); cards.pop(); cout << endl << "Remaining card: " << cards.front() << endl; } cards.pop(); } }
|