N个人围成一个圈,从第一个开始报数,报到3的推出圈子,问最后一个是原来的第几号。
如何才能让他们围成一个圈子呢?
还有,最后会剩1个或2个,又怎样放到前面去?
谁给我点头绪啊
不用循环数组
只要一个数组 用一个while语句两个if语句就搞定。
我的代码如下 是20个学生数到3就出队列。
#include <stdio.h>
void main ()
{
int stu[20] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19};
int cout = 0;
int cout1 = 3;
int *p = &stu[2];
int pu;
while ( cout <= 20 )
{
if ( cout1 == 3 )
{
cout1 = 0;
pu = p-stu;
printf (" %d ", stu[pu]);
stu[pu] = -1;
}
p = &stu[( ( ( p - stu ) + 1 ) % 20 )];
if (*p != -1)
{
cout = 0;
cout1++;
}
else cout++;
}
}
/*---------------------------------------------------------------------------
File name: C76-36.cpp
Author: HJin (email: fish_sea_bird [at] yahoo [dot] com )
Created on: 7/30/2007 19:12:41
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
===========================================================================
经典 76 道编程题 之 36:
36. 猴子选大王:
① N 只猴子站成一行,每隔 M 只从头到尾报数,反复进行,报过数的退出,打
印每次退出的猴子的编号,直到剩下一只为止。
② N 只猴子站成一行,每 M 只报数。先从头到尾,报到尾后,再返回从尾到头
报数,打印每次方向及过程,直到剩下二只时,以排到后面的(指报数方向)为大王。
③ N 只猴子围成一圈,从第 P 个开始,每隔 M 只报数,打印每次过程,只剩下
一个时为大王。
*/
#include <iostream>
using namespace std;
#define MAX 10000
int a[MAX+1];
int chooseKing(int n, bool simulate=false);
int main()
{
int n, king;
while(cin>>n)
{
if(n==0)
{
cout<<"Please input n (n > 0):\n";
continue;
}
king = chooseKing(n);
cout<<"The king is monkey #"<<king<<"."<<endl;
}
return 0;
}
int chooseKing(int n, bool simulate)
{
int i, s, left;
// a[i] = 1 means that the monkey is a candidate for the king
// = 0 means he is eliminated.
for(i=1; i<=n; ++i)
a[i] = 1;
s=0;
left = n;
// there is more than one monkey left
while(left>1)
{
if(simulate)
{
for(i=1; i<=n; ++i)
{
if(a[i])
cout<<i<<" ";
}
cout<<endl;
}
left=0;
for(i=1; i<=n; ++i)
{
s+=a[i];
if(s==3)
{
s=0;
a[i]=0;
}
left+=a[i];
}
}
for(i=1; i<=n; ++i)
if(a[i])
return i;
return -1; // will never reach here
}
That is coolest code for this problem. Would you explain the math? It seems to me a lot of combinatorics is going on here.
You don't need the outer loop. One loop is enough.
int chooseKing3(int n, int m)
{
int p=n*m;
while(p>n)
{
p-=n;
p+=(p-1)/(m-1);
}
return p;
}
[此贴子已经被作者于2007-7-31 12:18:51编辑过]