Uva10935 - Throwing cards away I

本文介绍了一种解决Uva10935问题的方法,该问题涉及典型的队列操作。通过逐步移除队列首部的两个元素,并将第二个元素重新插入队尾,直到队列中只剩下一个元素为止。文章提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.题目

题目链接:Uva10935

二.思路

典型的队列,对于每次的排,把第一个pop出来输出,第二个pop出来重新push进队尾,只剩1张牌的时候结束,注意只有一张牌时候的情况,详情看代码注释。

三.源代码

#include <iostream>
#include <queue>
using namespace std;
int main() {
  queue<int> cards;  //用队列做容器
  int n, temp1, temp2;
  while ((cin >> n) && (n != 0)) {
    for (int i = 1; i <= n; i++)
      cards.push(i);
    if (n == 1) {
        //如果n=1直接输出
      cout << "Discarded cards:" << endl << "Remaining card: 1" << endl;
      queue<int> empty;
      swap(cards, empty);
      continue;
    }
    cout << "Discarded cards: ";
    while (n >= 2) {
      temp1 = cards.front();//输出队头
      cards.pop();
      if (n == 2) //注意最后一个数据不需要逗号
        cout <<temp1 << endl;
      else
        cout<<temp1 << ", ";
      temp2 = cards.front();//第二个元素添加至队尾
      cards.pop();
      cards.push(temp2);
      n--;
    }
    cout << "Remaining card: " << temp2 << endl;
    queue<int> empty;  //清空容器
    swap(cards, empty);
  }
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值