王道机试指南 例题5.2 约瑟夫问题No. 2

题目:

代码:

#include <iostream>
using namespace std;

bool IsEmpty(int* arr,int n){//检查arr数组是否全为0
    for(int i=0;i<n;i++){
        if(arr[i]==1) return false;
    }
    return true;
}

int main(){
    int n,p,m;
    while(cin>>n>>p>>m && n!=0){
        int child[n]={0};//child数组表示该位置的小孩是否还在,1表示还在,0表示已经出局
        for(int i=0;i<n;i++)//初始化让所有编号的小孩都有效
            child[i]=1;

        int step=p-1;//初始位置编号为p
        int count=1;//从1开始报数
        while(IsEmpty(child,n)==0){
            if(count!=m && child[step]==1){//还没数到m
                count++;
                step=(step+1)%n;
            }
            else if(count==m && child[step]==1){//已经数到m
                child[step]=0;
                count=1;
                cout<<step+1<<" ";
            }
            else if(child[step]!=1){//如果该位置小孩已经出局,则直接跳过
                step=(step+1)%n;
            }
        }
        cout<<endl;
    }
    return 0;
}

运行结果:

全部评论

相关推荐

02-26 09:15
已编辑
蚌埠学院 golang
点赞 评论 收藏
分享
评论
点赞
7
分享

创作者周榜

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