题解 | 约瑟夫环

约瑟夫环

https://www.nowcoder.com/practice/e417cfe32c74416ca38247f619ddb322

#include <stdio.h>

int main() 
{
  int n,k,m,a[100],count=0,step;
  scanf("%d %d %d",&n,&k,&m);
  for(int i=0;i<n;i++)
  {
    a[i]=i;
  }
  int i=k;
  while(count<n-1)
{
    step=0;
    while(step<m)
    {
        if(a[i] != -1)
        {
            step++;
        }
        if(step<m) {
            i=(i+1)%n;
        }
    }

    while(a[i]==-1)
    {
        i=(i+1)%n;
    }
    a[i]=-1;
    count++;

    i = (i + 1) % n;
    while(a[i] == -1 && count < n-1)
    {
        i = (i + 1) % n;
    }
}
    for(int i=0;;i++)
    {
        if(a[i]!=-1)
        {
            printf("%d",a[i]);
            break;
        }
    }
  

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务