【OJ】约瑟夫环问题

《【OJ】约瑟夫环问题》《【OJ】约瑟夫环问题》

#include<stdio.h>
class Person{
public:
    int name;
    bool flag;
};


int main()
{
    int m = 0; // 一共m个人
    int n = 0; // 从1开始报数 报到n的那个人出列
    scanf("%d%d",&m,&n);
    n = n-1; // 等效报的那个数  等效为从0开始报数 报到n-1的那个人出列
    Person *person = new Person[m];
    // 初始化
    for(int i=0;i<m;i++){
        person[i].flag = false; //刚开始都没有出列
        person[i].name = i + 1; // 每个人的“姓名” 这里用数字来表示
    }
    int pt = 0; // “等效指针”
    int currentPerson = m; // 记录当前序列的人数
    for(int i=0;i<m;i++){ // 循环 “总人数”次
        int offset = n%currentPerson;   // pt应该偏移这么多
        int count = 0;  // 计数器
        while(count!=offset||person[pt].flag==true){ // 关键代码  条件的判断
            if(person[pt].flag==true){
                pt = (pt+1)%m;   // %m 的目的是为了保证pt这个"等效指针"不越过数组的边界
                continue;
            }
            pt = (pt+1)%m;
            count++;
        }
        printf("%d\n",person[pt].name);
        currentPerson--;    // 当前序列总人数减一
        person[pt].flag = true; // 修改那个出列的人的标记
    }

    delete[] person;// 释放动态数组
    return 0;
}

 

    原文作者:约瑟夫环问题
    原文地址: https://blog.csdn.net/CholenMine/article/details/84492559
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞