#include <stdlib.h>
#include <iostream.h>
#define MAX 100
int select(int m,int n)
{
int a[MAX];
int i;
int sum=0;
int c=m;
for(i=0;i<m;i++)
{
a[i]=1;
}
while(c!=1)
{
c=0;
for(i=0;i<m;i++)
{
sum+=a[i];
if(sum==n)
sum=a[i]=0;
c+=a[i];
}
}
for(i=0;i<m;i++)//对数组数据读一遍
if(a[i]==1)
return i;
}
void result()
{
int m;
int n;
cout<<"猴子总数m为:";
cin>>m;
cout<<"猴子数数n为:(n<m)";
cin>>n;
if(n==1)
cout<<"大王为第"<<m<<"个猴子"<<endl;
else
cout<<"大王为第"<<select(m,n)+1<<"个猴子"<<endl;
}
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
int listselect(int m,int n)
{
int i=1;
LNode *head;
LNode *p,*l;
l=head=(struct LNode *)malloc(sizeof(struct LNode));
head->data=i;
for(i=2;i<=m;i++)
{
p=(struct LNode *)malloc(sizeof(struct LNode));
p->data=i;
l->next=p;
l=p;
}
p->next=head;
LNode *q;
while(m>1)
{
for(i=1;i<n;i++)
{
q=head;
head=head->next;
}
head=q->next=head->next;
m--;
}
return head->data;
}
void listresult()
{
int m;
int n;
cout<<"猴子总数m为:";
cin>>m;
cout<<"猴子数数n为:(n<m)";
cin>>n;
if(n==1)
cout<<"大王为第"<<m<<"个猴子"<<endl;
else
cout<<"大王为第"<<listselect(m,n)<<"个猴子"<<endl;
}
int main()
{
while(1)
{
cout<<endl<<endl<<"\t\t\t*******猴子选大王******\t\t\t"<<endl;
cout<<"\t\t\t* 1、顺序存储结构选取 *"<<endl;
cout<<"\t\t\t* 2、链式存储结构选取 *"<<endl;
cout<<"\t\t\t***********************"<<endl;
cout<<"\t\t\t 请选择:";
int a;
cin>>a;
system("cls");
switch(a)
{
case 1: result();break;
case 2: listresult();break;
default: return(0);
}
}
}