题目链接:https://vjudge.net/problem/UVA-10935
桌上有n(n≤50)张牌,从第一张牌(即位于顶面的牌)开始,从上往下依次编号为1~ n。当至少还剩下两张牌时进行以下操作:把第一张牌扔掉,然后把新的第一张牌放到整叠 牌的最后。输入每行包含一个n,输出每次扔掉的牌以及最后剩下的牌。
分析:直接上队列。参考 STL 中队列的使用
头文件:#include<queue>
基本操作:
push(x) 将x压入队列的末端
pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值
front() 返回第一个元素(队顶元素) (优先队列取队首元素是top() )
back() 返回最后被压入的元素(队尾元素)
empty() 当队列为空时,返回true
size() 返回队列的长度
本题代码:
#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
int main(){
int n;
queue<int> q;
while(cin>>n&&n){
int first=1;
cout<<"Discarded cards:";
for(int i=1;i<=n;i++){
q.push(i);
}
while(q.size()>1){
if(first==1){printf(" %d",q.front()); first=0;}
else printf(", %d",q.front());
q.pop();
int p=q.front();
q.pop();
q.push(p);
}
printf("\nRemaining card: %d\n",q.front());
q.pop();
}
return 0;
}
//Discarded cards: 1, 3, 5, 7, 4, 2
//Remaining card: 6