62- prove safety offer- face questions circle last remaining figures - Josephus - Method 1

/*
topic:
    Josephus problem.
Ideas:
    List implemented using a linked list, the linked list at the end of the note is determined, so that the beginning point,
    Each cycle to delete a number until only one digit.
*/
#include<iostream>
#include<list>

using namespace std;

int LastRemaining(unsigned int n,unsigned int m){
    if(n < 1|| m < 1) return -1;
    list<int> numbers;
    for(int i = 0; i < n; i++){
        numbers.push_back(i);
    }
    list<int>::iterator current = numbers.begin();
    while(numbers.size() > 1){
        for(int i = 1; i < m; i++){
            current++;
            if(current == numbers.end()){
                current = numbers.begin();
            }
        }
        list<int>::iterator next = ++current;
        if(next == numbers.end()){
            next = numbers.begin();
        }
        --current;
        numbers.erase(current);
        current = next;
    }
    return *current;

}

int main () {
    cout<<LastRemaining(5,3);
}

  

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/12130338.html