DEV Community

Guhan M
Guhan M

Posted on Edited on

Josephus Problem I | CSES - Algoritmit ongelmanratkaisussa

Josephus Problem I - Problem link

Indexed set solution

#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <utility>
#include <unordered_set>
#include <unordered_map>
#include <cmath>
#include <climits>
#include <cinttypes>
#include <algorithm>
#include <ext/pb_ds/assoc_container.hpp>

using namespace std;
using namespace __gnu_pbds;

typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> indexed_set;

typedef long long ll;
typedef long int longi;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<pii> vpii;
template <class T> int size(const T &x) { return x.size(); }
const int INF = 2147483647;
#define repn(i,n) for (__typeof(n) i=0; i<(n); ++i)
#define rep(i,a,b) for (__typeof(a) i=(a); i<(b); ++i)
#define iter(it,c) for (__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;
    indexed_set iset;
    repn(i, n) {
        iset.insert(i + 1);
    }
    int idx = 1;
    while (iset.size() > 1) {
        int num = *iset.find_by_order(idx);
        cout << num << ' ';
        iset.erase(num);
        // if (iset.size() > 0)
        idx = (idx + 1) % iset.size();
    }
    cout << *iset.find_by_order(0) << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Deque solution

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

typedef long long ll;

int main() {
    int n;
    cin >> n;

    queue<int> q;
    for (int i = 1; i <= n; i++) {
        q.push(i);
    }

    bool flag = false;
    while (!q.empty()) {
        int child = q.front();
        q.pop();

        if (flag) {
            cout << child << ' ';
        } else {
            q.push(child);
        }
        flag = !flag;
    }
    cout << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)