【刷题】【stl】士兵队列训练问题
题目:
某部队进行新兵队列训练,将新兵从一开始按顺序依次编号,并排成一行横队,训练的规则如下:从头开始一至二报数,凡报到二的出列,剩下的向小序号方向靠拢,再从头开始进行一至三报数,凡报到三的出列,剩下的向小序号方向靠拢,继续从头开始进行一至二报数...以后从头开始轮流进行一至二报数、一至三报数直到剩下的人数不超过三人为止。
输入数据
本题有多个测试数据组,第一行为组数N,接着为N行新兵人数,新兵人数不超过5000。
输出数据
共有N行,分别对应输入的新兵人数,每行输出剩下的新兵最初的编号,编号之间有一个空格。
输入样例 输出样例
2 1 7 19
20 1 19 37
40
方法一:队列模拟
利用队列先进先出的特点,开两个队列,从头到尾,进行报数加上踢人
#include<bits/stdc++.h> using namespace std; int T,n; queue <int > q[2]; int main() { cin>>T; while(T--) { while(!q[0].empty() ) q[0].pop(); while(!q[1].empty() ) q[1].pop(); cin>>n; for(int i=1;i<=n;i++) q[0].push(i); int cnt=n,nw=1,pre=0; for(int i=1;cnt>3;i++) { if(i%2==1)//报到2出列 { int tm=0; while(!q[pre].empty() ) { ++tm; if(tm==2) tm=0,cnt--; else q[nw].push(q[pre].front() ); q[pre].pop(); } } else//报到3出列 { int tm=0; while(!q[pre].empty() ) { ++tm; if(tm==3) tm=0,cnt--; else q[nw].push(q[pre].front() ); q[pre].pop(); } } pre=nw,nw=1-pre; } while(!q[0].empty() ) //最后肯定是一个空一个不空,总之都输出就对了 { cout<<q[0].front()<<" "; q[0].pop(); } while(!q[1].empty() ) { cout<<q[1].front()<<" "; q[1].pop(); } cout<<endl; } return 0; }
方法二:列表list
如果记得list的操作函数,可以利用list删除元素的便利性,只开一个list,数到了2/3就删除元素
#include<bits/stdc++.h> using namespace std; list <int > ls0; list <int > ::iterator it ; int main() { int T,n; cin>>T; while(T--) { for(it=ls0.begin();it!=ls0.end(); ) it=ls0.erase(it); cin>>n; for(int i=1;i<=n;i++) ls0.push_back(i); for(int i=1; ls0.size()>3 ;i++) { if(i%2==1)//报到2出列 { int tm=0; for(it=ls0.begin();it!=ls0.end(); ) { ++tm; if(tm==2) { tm=0; //cout<<*it<<endl; it=ls0.erase(it);//不能删了再加加 } else it++; } } else//报到3出列 { int tm=0; for(it=ls0.begin();it!=ls0.end(); ) { ++tm; if(tm==3) { tm=0; //cout<<*it<<endl; it=ls0.erase(it);//不能删了再加加 } else it++; } } } for(it=ls0.begin();it!=ls0.end();it++) cout<<*it<<" "; cout<<endl; } return 0; }