用队列处理约瑟夫环问题(C++)
#include<iostream>
#include<malloc.h>
using namespace std;
const int maxsize=50;
typedef struct//创建循环队结构体
{
int data[maxsize];
int front,rear;
}Squeue;
void CreateQueue(Squeue *&s)//初始化循环队 函数
{
s=(Squeue *)malloc(sizeof(Squeue));
s->front=s->rear;
}
bool EnQueue(Squeue *&s,int e)//入队函数
{
if((s->rear+1)%maxsize==s->front)
return false;//队满
s->rear=(s->rear+1)%maxsize;
s->data[s->rear]=e;
return true;
}
bool DeQueue(Squeue *&s,int &e)//出队函数
{
if(s->front==s->rear)
return false;
s->front=(s->front+1)%maxsize;
e=s->data[s->front];
return true;
}
bool EmptyQueue(Squeue *s)//判断循环队是否为空
{
if(s->front==s->rear)
return true;
else
return false;
}
int main()
{
int a,b,e;
Squeue *s;
CreateQueue(s);
cout<<"输入队的长度: "<<endl;
cin>>a;
cout<<"输入报的数: "<<endl;
cin>>b;
for(int i=1;i<=a;i++)
{
EnQueue(s,i);//根据队伍的长度入队
}
if(b==1)//报数为1出队时,全部出队
{
while(!EmptyQueue(s))
{
DeQueue(s,e);
cout<<e<<" ";
}
}
else
{
while(!EmptyQueue(s))
{//报到数为b的人出队,b-1前的人出队后重新入队
for(int j=1;j<=b-1;j++)
{
DeQueue(s,e);
EnQueue(s,e);
}
DeQueue(s,e);
cout<<e<<" ";
}
}
return 0;
}
输入:8 3
输出:
3 6 1 5 2 8 4 7
输入队的长度:
8
输入报的数:
3
3 6 1 5 2 8 4 7
--------------------------------
Process exited after 3.565 seconds with return value 0
请按任意键继续. . .

该博客介绍了如何利用C++的循环队列数据结构解决约瑟夫环问题。通过创建一个循环队列,博主演示了如何根据队伍长度和报数来模拟过程,当报到特定数时将人员出队。程序首先初始化队列,然后根据输入的队伍长度和报数进行循环操作,最终输出剩余的序列。
3496

被折叠的 条评论
为什么被折叠?



