# 猴子选大王问题算法，求完整代码！

abcd321we 2006-04-16 05:29:39

...全文
217 5 点赞 打赏 收藏 举报

5 条回复

abcd321we 2006-04-16

• 打赏
• 举报

chenhu_doc 2006-04-16

• 打赏
• 举报

chenhu_doc 2006-04-16
//写的代码比较长，但是绝对好懂···
• 打赏
• 举报

chenhu_doc 2006-04-16

#include <iostream>
#include <iomanip>
using namespace std;

typedef struct LNode{
int NO;
struct LNode * next;
}Lnode, *Josephus;

Josephus InitJosephus()
{
LNode * head = new LNode;
}

Josephus CreateJosephus(int enjoyIn)
{
LNode * node = NULL;

for( int i = 1; i <= enjoyIn; i++ )
{
node = new LNode;
node->NO = i;
forword->next = node;
forword = forword->next;
node->next = NULL;
}
}

void JoseProcess( Josephus &Jose, int position, int cycle)
{
Josephus p = Jose->next;
Josephus qTemp = NULL;
int temp;
for(int i = 0; i < position-1; i++ )
{
p = p->next;
}
cout<<"Out of the queue... "<<endl;

if(cycle == 1 && p->next != p)
{
qTemp = p;
while( qTemp->next != p )
qTemp = qTemp->next;
}
if(cycle == 1 && p->next == p)
{
cout<<"The winner is "<< p->NO <<" child! "<<endl;

}
while( p->next != p )
{

for(int j = 1; j < cycle; j++ )
{
qTemp = p;
p = p->next;
}

temp = p->NO;

qTemp->next = p->next;
delete p;
p = qTemp->next;
cout<<temp<<endl;
}
cout<<"The winner is "<< p->NO <<" child! "<<endl;
}

void main()
{
int enjoyIn;
int position;
int cycle;

cout<<"the total of the children : ";
cin>>enjoyIn;
cout<<endl<<"the position you want to access : ";
cin>>position;
cout<<endl<<"the cycle you want : ";
cin>>cycle;
cout<<endl;

Josephus Jose = CreateJosephus( enjoyIn );
JoseProcess( Jose, position, cycle);
}
• 打赏
• 举报

kingerwt 2006-04-16
//猴子选大王问题！
#include<iostream.h>

int choose(int num,int del)
{
int i;
int a[100];
for(i=0;i<num;i++)
a[i]=1; //猴子状态初始化，为1表示可能被选上，为0表明没希望了；

int sum=0, //循环记数；
countOne=num; //累积记数初始化，大于1表明还有大王候选人；

while(countOne>1)
{
countOne=0;
for(i=0;i<num;i++)
{
sum+=a[i];
if(sum==del)
sum=a[i]=0; //淘汰倒霉猴子；
countOne+=a[i];
}
}

for(i=0;i<num;i++)
if(a[i]!=0)
return i; //找到幸运猴子编号（从0开始的）；
}

void main()
{
int num,del;
cout<<"请输入猴子总数："<<endl;
cin>>num;
cout<<"请输入淘汰第几个："<<endl;
cin>>del;
if(del>0)
{
if(del==1)
{
cout<<"所有猴子都删了拉，哪还有什么大王类！"<<endl;
}
else
{
cout<<"第"<<choose(num,del)+1<<"个猴子为王！"<<endl;
}
}
else cout<<"都不删，你耍我呀!"<<endl;
}

• 打赏
• 举报

3.3w+

C/C++ 新手乐园

2006-04-16 05:29