Skip to content

Commit 86907fd

Browse files
C++ implementation of Josephus problem (#913)
1 parent 0721676 commit 86907fd

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Problem statement - Consider a game where there are n children(numbered 1,
2+
// 2,…, n) in a circle.During the game, every second child is removed from the
3+
// circle, until there are no children left.In which order will the children be
4+
// removed?
5+
6+
// problem link - https://cses.fi/problemset/task/2162/
7+
8+
#include <bits/stdc++.h>
9+
#define ll long long
10+
using namespace std;
11+
12+
void solve() {
13+
ll n;
14+
cin >> n;
15+
set<ll> s;
16+
for (int i = 1; i <= n; i++) s.insert(i);
17+
auto it = s.begin();
18+
ll c = 0;
19+
ll cnt = n;
20+
while (cnt != 1) {
21+
--cnt;
22+
if (c < 1) {
23+
++c;
24+
++it;
25+
}
26+
if (it == s.end())
27+
it = s.begin();
28+
if (c) {
29+
cout << *it << " ";
30+
31+
s.erase(it++);
32+
if (it == s.end())
33+
it = s.begin();
34+
c = 0;
35+
if (it == s.end())
36+
it = s.begin();
37+
}
38+
}
39+
cout << *s.begin() << endl;
40+
}
41+
//----------------------Main----------------------------//
42+
43+
int main() {
44+
FIO;
45+
46+
// test case - 7
47+
// output - 2 4 6 1 5 3 7
48+
49+
solve();
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)