ACWING82. Circle last remaining numbers (to prove safety offer, Joseph problems)

0, 1, ..., n-1 of the n numbers (n> 0) are arranged in a circle, each deletion from the m-th digit numbers beginning from 0 the circle.

Find the circle where the last remaining digit.

Sample
input: n = 5, m = 3

Output: 3

Ideas:
Solution one: Analog list

Solution II: Mathematical Methods:
Let n individual survivors when we get to x, then the first individual time n + 1, m-th individual will certainly die, it will remove the m individual, every m-bit digital moving forward (m-1 before the digital sequentially moved to the back), which when transformed into n individual case, the case needs to move to the right resulting x n + 1 is m bits when individual survivors.

The results are: f [ n ] = ( f [ n 1 ] + m ) m o d    n f[n] = (f[n - 1] + m) \mod n

Simulation Algorithm

#include <list>
class Solution {
public:
    int lastRemaining(int n, int m){
        list<int>lis;
        for(int i = 0;i < n;i++) lis.push_back(i);
        auto it = lis.begin();
        while(lis.size() != 1) {
            for(int i = 1;i <= m - 1;i++) {
                it++;
                if(it == lis.end()) it = lis.begin();
            }
            it = lis.erase(it);
            if(it == lis.end()) it = lis.begin();
        }
        return lis.front();
    }
};

Mathematical solution

class Solution {
public:
    int lastRemaining(int n, int m){
        vector<int>f(n + 1,0);
        f[0] = 0;
        for(int i = 1;i < n;i++) {
            f[i] = (f[i - 1] + m) % (i + 1);
        }
        return f[n - 1];
    }
};
Published 844 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104974269
Recommended