猴子选大王问题算法,求完整代码!

abcd321we 2006-04-16 05:29:39
急用,马上给分!快快快啊
...全文
256 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
abcd321we 2006-04-16
  • 打赏
  • 举报
回复
谢谢了~~~呵呵~~只要能交差就好了
chenhu_doc 2006-04-16
  • 打赏
  • 举报
回复
一个部落的猴子肯定很多,那么用链表实现绝对是首选////
哈,中间的void JoseProcess( Josephus &Jose, int position, int cycle)
就是主要的部分,写的代码比较长,但是考虑的东西也是比较全面的。。。
chenhu_doc 2006-04-16
  • 打赏
  • 举报
回复
//写的代码比较长,但是绝对好懂···
chenhu_doc 2006-04-16
  • 打赏
  • 举报
回复
什么猴子选大王呀,不就是josephus呀
我也写了,用的是循环链表

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

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

Josephus InitJosephus()
{
LNode * head = new LNode;
head->next = head;
head->NO = 0;
return head;
}

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

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

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;
}


以前写过的~~看看能不能用的上

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧