C ++ learning algorithm / Joseph problems of bad guys must die a good man can not die


Rules of the game are: total number of 2 * k personal newspaper, in front of k is a good man, bad man behind the k is the number of gettin from a good man, who reported m to die. And then continue to count off scratch a living from the dead, reported m of people died, and so on. When k = 12 when asked what the value of m, there will be no bad all good die prior to die. (From experiments it)

Procedures are as follows:

#include <iostream>

using namespace std;

const int P = 24;

int per[24];

void init(){    //游戏参与者初始化
    for(int i = 0; i < 24; i++){
        per[i] = 1;
    }
}

//算法测试检验
void print(){
    for(int i = 0; i < 24; i++){
        cout << i << "|" << per[i] << " ";
        if(i%6 == 0 && i != 0){
            cout << endl;
        }
    }
}

bool getP(int N, int start,int livers){
    if(livers < 13){
        return true;
    }
    //该处代码省略
    int index = start;      //检验下一个人存活的位置
    for(int i = 0; i < leave-1;){
        //找到一个存活的人就继续寻找下一个
        if(per[index] == 1){
            i++;
            if(index+1 == 24){
                index = 0;
            }else{
                index += 1;
            }
        }else{
            //由于数组范围为24所以,不能越界
            if(index+1 == 24){
                index = 0;
            }else{
                index += 1;
            }
        }
    }
    //寻找死亡的人
    while(true){
        if(per[index] == 1){
            if(index < 12){ //如果死了一个好人,则不满足规则,返回再来下一个数字
                return false;
            }
            per[index] = 0;
            break;
        }else{
            if((index+1) == 24){
                index = 0;
            }else{
                index += 1;
            }
        }
    }
    //确定下一个开始位置
    int next;
    /该处代码省略...
    getP(N, next, livers-1);
}

int main()
{
    init();
    for(int i = 1; i; i++){
        if(getP(i, 0, 24)){
            cout << i << "!!" << endl;
            print();
            break;
        }
        init();
    }
}
The above procedure codes have been omitted if students really like algorithm on her own, because much of this problem algorithm design, but optimization algorithm
Published 31 original articles · won praise 3 · views 10000 +

Guess you like

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