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

abcd321we 2006-04-16 05:29:39
急用,马上给分!快快快啊
...全文
217 5 点赞 打赏 收藏 举报
写回复
5 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
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;
}


以前写过的~~看看能不能用的上
  • 打赏
  • 举报
回复
相关推荐
发帖
新手乐园
加入

3.3w+

社区成员

C/C++ 新手乐园
申请成为版主
帖子事件
创建了帖子
2006-04-16 05:29
社区公告
暂无公告