循环队列解决约瑟夫问题
生活随笔
收集整理的這篇文章主要介紹了
循环队列解决约瑟夫问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有n個人圍成一圈,從第1個人開始,1,2,…,m報數,報至m出局,余下的人繼續從1,2,…,m報數,重復之前的流程,要求:求出被淘汰編號的序列,及最后剩下的一人是
原來的第幾號?(要求:用循環隊列解決該問題。)
?
#ifndef STATUS_H #define STATUS_H#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status;#endif?
#include <iostream> using namespace std; #include "Status.h" typedef int ElemType; typedef struct { ElemType *base; int front; int rear; int MAXSIZE; }SqQueue; Status InitQueue(SqQueue& Q,int n) //初始化隊列 { Q.base = new ElemType[100]; if(!Q.base) { cout << "創建隊列失敗!"; return ERROR; } Q.front=Q.rear=0; Q.MAXSIZE = n+1;//MAXSIZE是總人數+1,是為了留出一個空位置來放置rear return OK; } void QueueTraverse(SqQueue Q) //遍歷隊列 { int i; i=Q.front; while(i!=Q.rear) { cout<<Q.base[i]<<" "; i=(i+1)%Q.MAXSIZE; } cout<<endl; } Status EnQueue(SqQueue& Q,ElemType e) //入隊 { if((Q.rear+1)%Q.MAXSIZE==Q.front) { cout << "隊列已滿!"; return ERROR; } Q.base[Q.rear] = e; Q.rear = (Q.rear+1)%Q.MAXSIZE; return OK; } Status DeQueue(SqQueue& Q,ElemType& e) //出隊 { if(Q.front==Q.rear) { cout << "隊列為空!"; return ERROR; } e = Q.base[Q.front]; Q.base[Q.front] = 0; Q.front = (Q.front+1)%(Q.MAXSIZE-1);//總人數為MAXSIZE-1return OK; }int main() { int n,m,i=1; SqQueue Q; ElemType e; cout << "請輸入n個人(n<=100):";do{ cin >> n; if(n>100 || n<1) { cout << "輸入人數錯誤!請重新輸入:"; } }while(n>100 || n<1);InitQueue(Q,n); while(i<=n)//入隊操作 { EnQueue(Q,i); i++; } cout << "\n此時的序列順序為:"<<endl; QueueTraverse(Q); cout << "\n請輸入第m個人出隊(1<=m<=n):"; do{ cin >> m; if(m>n || m<1) { cout << "m輸入錯誤!請重新輸入:"; }}while(m>n || m<1);cout << endl; int Count = n;//用來記錄剩下的人數 while(Count != 1) { i = 1;//i用來控制是第幾個人報數 while(i != m)//當i的值不等于m的值時 { Q.front = (Q.front+1)%(Q.MAXSIZE-1);//總人數為MAXSIZE-1 if(Q.base[Q.front] != 0)//當此時不為0的話,i++用來控制第幾個人 { i++; } } DeQueue(Q,e); while(Q.base[Q.front] == 0)//當此時為0的時候,循環找到下一個不為0的位置 { Q.front = (Q.front+1)%(Q.MAXSIZE-1); } cout << "序號:" << e << "出局!\n"; Count--; } DeQueue(Q,e); cout << "\n最后一個是:" << e << endl; return 0; }?
?
1.? 有n個人圍成一圈,從第1個人開始,1,2,…,m報數,報至m出局,余下的人繼續從1,2,…,m報數,重復之前的流程,要求:求出被淘汰編號的序列,及最后剩下的一人是原來的第幾號?(要求:用循環隊列解決該問題。)
轉載于:https://www.cnblogs.com/luoyanghao/p/6197664.html
總結
以上是生活随笔為你收集整理的循环队列解决约瑟夫问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Bootsrap基本应用
- 下一篇: 爱的世界很拥挤,写在读《爱,就这么简单》