C ++ algorithms to learn / find the last survivors of Joseph problems

Rules of the game: n individuals in a circle, began to repeat the count from the first person, each number to 2 (!! Please note that this is a different question and classic Joseph), to kill this position, while leaving other people. But I do not want this to be killed Joseph. He determined the position of the last survivors, and stood there. We remember who survived the position number is A. (From experiments it)

Procedures are as follows:

#include <iostream>

using std::cout;
using std::endl;

//程序测试
int main()
{
    int num = 1111;             //最大数
    int base = (num+1)/2;       //所有数,且省去了第一次判断最大是否存活
    bool flag = true;           //判断最大数是否继续存在,即开始的位置是奇数还是偶数, 1代表奇数(存活), 0代表偶数(死亡).
    int sub = 1;                //最大数减去的基数
    while(base >= 2){           //直至所有数 >= 都要继续循环,直至找到最后的最大数,num存放的就是最大数
        sub *= 2;
        if(flag){
            if(base%2 != 0){
                num -= sub;
             	//此处代码省略
                base -= 1;
                base /= 2;
            }else{
                base /= 2;
            }
        }else{
            if(base%2 == 0){
                num -= sub;
                base /= 2;
            }else{
                base += 1;
                base /= 2;
                //此处代码省略
            }
        }
    }
    cout<<"最后活下来的数字是: "<<num<<endl;
}

This procedure does not solve the problem, just get the final figures, comment much, but the idea has been almost, omitted part of the code above there, like algorithm students can study ...



Published 31 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_36557960/article/details/78572878