士兵队列训练问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12321 Accepted Submission(s): 5441
Problem Description
某部队进行新兵队列训练,将新兵从一开始按顺序依次编号,并排成一行横队,训练的规则如下:从头开始一至二报数,凡报到二的出列,剩下的向小序号方向靠拢,再从头开始进行一至三报数,凡报到三的出列,剩下的向小序号方向靠拢,继续从头开始进行一至二报数。。。,以后从头开始轮流进行一至二报数、一至三报数直到剩下的人数不超过三人为止。
Input
本题有多个测试数据组,第一行为组数N,接着为N行新兵人数,新兵人数不超过5000。
Output
共有N行,分别对应输入的新兵人数,每行输出剩下的新兵最初的编号,编号之间有一个空格。
Sample Input
2 20 40
Sample Output
1 7 19 1 19 37
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
#define N 5001
struct queue //定义队列结构体
{
int f,r,data[N];
void init(){
f=r=0;
}
void push(int a) //入队
{
data[r++]=a;
}
int gettop()
{
return data[f++];
}
bool judge(){ //检查对内元素个数是否小于4个
return r-f<4;
}
bool empty() //判断队列是否为空
{
return r==f;
}
}q[2];
int main()
{
int T,n,i;
cin>>T;
while(T--)
{
cin>>n;
q[0].init(),q[1].init();
for(i=1;i<=n;i++)
{
q[0].push(i);//将n个人依次加入队列
}
int now=0,pre=1;
i=0;
while(!q[now].judge())
{
q[pre].init();
if(i&1)
{
while(!q[now].empty())
{
q[pre].push(q[now].gettop());
if(q[now].empty())
break;
q[pre].push(q[now].gettop());
if(q[now].empty())
break;
q[now].gettop();
}
}
else
{
while(!q[now].empty())
{
q[pre].push(q[now].gettop());
if(q[now].empty())
break;
q[now].gettop();
}
}
i^=1;
swap(now,pre);//交换工作队列
}
cout<<q[now].gettop();
while(!q[now].empty())
{
cout<<' '<<q[now].gettop();
}
}
return 0;
}