turbo pascal 一维数组题(猴子选大王)

来源:百度知道 编辑:UC知道 时间:2024/05/14 04:16:50
有N只猴子围成一圈,每只猴子各一个从1到N中的依次编号,打算从中选出一个大王;经过协商,决定出选大王的规则:从第一个开始循环报数,数到M的猴子出圈,最后剩下来的就是大王。要求:从键盘输入N、M,编程计算哪一个编号的猴子成为大王
样例:
输入:7 3
输出:4

program king;
var
a:array[1..2000] of 0..1;
i,m,n,p,s:longint;
begin
readln(n,m);
fillchar(a,sizeof(a),1);
i:=0;
for s:=1 to n-1 do
begin
p:=0;
while p<m do
begin
i:=i+1;
if i>n then i:=1;
if a[i]=1 then p:=p+1;
end;
a[i]:=0;
end;

for i:=1 to n do
if a[i]=1 then
writeln(i);
end.

经典的约瑟夫问题,建议你去看看解题报告,有很多变形...
以下的程序以调译通过,由于你没有给出数据规模,所以数组和变量的数据范围你自己调吧,在整形范围内是可以过的。
program Joseph;
var
n,m,i,j,nt:longint;
h:array[1..32767]of boolean;
begin
readln(n,m);
nt:=0;
for i:=1 to n do
h[i]:=true;
for i:=1 to n-1 do
begin
j:=0;
repeat
inc(nt);
if nt>n then nt:=1;
if h[nt] then inc(j);
until j=m;
h[nt]:=false;
end;
for i:=1 to n do
if h[i] then writeln(i);
end.