Josephus Problem II

Consider a game where there are n children (numbered ) in a circle. During the game, repeatedly children are skipped and one child is removed from the circle. In which order will the children be removed?

Example:

Input:  n = 7 , k = 2
Output: 3 6 2 7 5 1 4 

Approach

C++

#include <bits/stdc++.h>
using namespace std;

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <class T>
using ordered_set = tree<Tnull_typeless<T>, rb_tree_tagtree_order_statistics_node_update>;
template <class Kclass V>
using ordered_map = tree<KVless<K>, rb_tree_tagtree_order_statistics_node_update>;

vector<intjosephusProblemII(int nint k)
{

    vector<inta(n);

    vector<intres;
    iota(a.begin(), a.end(), 1);
    ordered_set<intos(a.begin(), a.end());
    int pos = 0;
    while (os.size())
    {
        pos = (pos + k) % (os.size());
        res.push_back(*os.find_by_order(pos));
        os.erase(os.find_by_order(pos));
    }
    return res;
}

int main()
{
    int n = 7k = 2;

    vector<intres = josephusProblemII(nk);

    for (int i = 0i < res.size(); i++)
        cout << res[i] << " ";

    return 0;
}

No comments:

Post a Comment