约瑟夫环问题

来源:百度知道 编辑:UC知道 时间:2024/05/10 18:03:09
#include<stdio.h>
main()
{
int a[31];
int n,s,m,i,j,k=0,x,y,z;
scanf("%d %d %d",&n,&s,&m);
for(y=1;y<=n;y++)
a[y]=y;
if(n<m+s-1)
for(i=s+m-n-1;i<=n;i=i+m)
a[i]=0;
else
for(i=s+m-1;i<=n;i=i+m)
a[i]=0;
if((i-m)==n)z=0;
else
{
if(i!=n)
{z=i-n;a[z]=0;}
else z=0;
}
x=0;
for(j=1;j<=15;j++)
{
x=0;
for(i=z+1;i<=n;i++)
{
z=0;
if(a[i]!=0)k++;
if(k==m){a[i]=0;k=0;}
}
for(y=1;y<=n;y++)
if(a[y]!=0)x++;
if(x==1)break;
}
for(y=1;y<=n;y++)
if(a[y]!=0)j=y;
printf("%d",j);
}
请问错在哪里?

#include <stdio.h>
#include <malloc.h>
#include <memory.h>
//pLeft长度固定为N, 表示队伍中留下人的位置.nLeave是离开的人数, 判断结束
//输出是依次从队伍中离开的人的序号.
int fun(unsigned char *pLeft, int N, int *nLeave, int m, int nStart)
{
int nCount=0,nPoint=nStart;
if(pLeft[nPoint]==1)
nCount++;
while(nCount<m)
{
nPoint=nPoint%N+1;
if(pLeft[nPoint]==1)
nCount++;
}
(*nLeave)++;
pLeft[nPoint]=0;
return nPoint;
}

void main(int argc, char *argv[])
{
int n=0,m=0,nLeave=0,nStart=1;
printf("输入 人数n,上限m.\n");
scanf("%d,%d",&n,&m);
unsigned char *pLeft=(unsigned char *)calloc(n+1,sizeof(char));
memset(pLeft,1,(n+1)*sizeof(char));
while(nLeave<n)
printf("%d\t",nStart=fun(pLeft, n, &nLeave, m, nStart));
free(pLeft);
}

---------输出,20个人,m=26------------
输入 人数n,上限m.
20,26