因为这个专题是栈和队列,所以写好队列类直接用在所有题目上了,代码有些冗长,毕竟好多成员函数都不是这个题用得到的。。。本题的思想就是模拟,先将士兵按序入队,然后分别执行2、3出队操作,需要注意的是因为此题队列使用的是链表式结构,如果士兵是边报数边出列的话,每当有士兵出列的时候,剩下的士兵序号都会发生改变,所以这时候就要稍加变动了。
如果先不考虑出队士兵对队列序号的影响的话,当报数为2时,需要出列的士兵编号是1 2 3 4 5 6 7 8 ...如红色部分,序号是2,4,6,8,如果考虑出队对整体序号的影响,那么2号士兵出队以后,4号士兵的序号就变成了3,6号变成了5,当4号士兵出列的时候,6号士兵的序号变成了4.。。所以出列的序号是2,3,4.。。。同样报数为3的时候也同理,这样就可以根据这个规律来模拟士兵出列了,代码如下:
#include <iostream>
#include <cstdlib>
using namespace std;
typedef int anytype;
struct queues
{
int cont;
struct node //该队列用链表创建,方便任意位置出队
{
anytype data;
struct node *next;
}*head,*tail;
queues() //默认构造函数
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
cont=0;
}
bool empty() //判断空队
{
if(cont)
return false;
return true;
}
void push(anytype n) //入队操作
{
struct node *p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=NULL;
tail->next=p;
tail=p;
cont++;
}
void pop() //出队操作
{
struct node *p=head->next;
head->next=p->next;
free(p);
cont--;
}
void leave(int n) //任意位置出队
{
struct node *p=head->next,*q=head;
if(n<=cont)
{
for(int i=1;i<n;i++)
{
q=p;
p=p->next;
}
q->next=p->next;
free(p);
cont--;
}
}
anytype front() //查询队头
{
return head->next->data;
}
anytype back() //查询队尾
{
return tail->data;
}
anytype ask(int n) //查询任意位置
{
struct node *p=head;
if(n<=cont)
{
for(int i=0;i<n;i++)
p=p->next;
return p->data;
}
return 0;
}
int count() //查询对内元素数
{
return cont;
}
};
int main()
{
ios::sync_with_stdio(false);
int t,n;
cin>>t;
while(t--)
{
queues s;
cin>>n;
for(int i=1;i<=n;i++)
s.push(i); //士兵入队
for(int i=2;s.cont>3;i=((i+1)%2+2)) //按照顺序出队
for(int j=i;j<=s.cont;j+=(i-1))
s.leave(j);
for(int i=1;i<=s.cont;i++)
{
if(i!=1)
cout<<" ";
cout<<s.ask(i); //输出剩余士兵的编号
}
cout<<endl;
}
return 0;
}