约瑟夫环问题问题描述:
约瑟夫环问题的一种描述是:编号为1,2,…,n的n个人按顺时针方向围坐一圈,每人持有一个密码(正整数)。一开始任选一个整数作为报数上限值m。从第一个人开始顺时针自1开始顺序报数,报到m时停止报数。报m的人出列,将他的密码作为新的m值,从在顺时针方向上的下一个人开始重新从1报数,如此下去,直至所有人全部出列,试设计一个程序,求出出列顺序。
解决方法:
利用单向循环链表作为存储结构模拟此过程,按照出列顺序打印出各人的编号。
#include<iostream>
using namespace std;
typedef struct LNode{
int num; //编号
int code; //密码
struct LNode *next;
}LNode,*LinkList;
void CreatList(LinkList &L,int n){
L=new LNode; //创建的链表不能有头结点!!!
L->num=1; //创建的链表不能有头结点!!!
cin>>L->code; //创建的链表不能有头结点!!!
L->next=L;
LNode *r=L;
for(int i=1;i<n;++i){
LNode *p=new LNode;
p->num=i+1;
cin>>p->code;
p->next=L;
r->next=p;
r=p;
}
}
void Sequence(LinkList &L,int m){
int count;
LNode *p=L;
LNode *q=p->next;
while(p!=q){
count=1;
while(count<m-1){
p=p->next;
++count;
}
q=p->next;
cout<<q->num<<" ";
m=q->code;
p->next=q->next;
/*---------------这一句很重要---------------*/
/*-----当出列的这个人的密码为1的时候需要特殊处理-----*/
if(q->code!=1) p=q->next;
/*-----当出列的这个人的密码为1的时候需要特殊处理-----*/
/*---------------这一句很重要---------------*/
delete q;
}
}
int main(){
int n,m;
LinkList L;
cout<<"Enter the number of the people:";
cin>>n;
cout<<"Enter the codes:"<<endl;
CreatList(L,n);
LNode *p=L;
cout<<"Enter the m:";
cin>>m;
Sequence(L,m);
return 0;
}
例如m的初值为20;n=7,7个人的密码依次为3,1,7,2,4,8,4,出列的顺序为6,1,4,7,2,3,5。