用队列处理约瑟夫环问题(C++)

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

用队列处理约瑟夫环问题(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
请按任意键继续. . .
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值