Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Input:
- 2
- 4 1 2
- 5 2 3
- Output:
- 2
- 1
- #include <iostream>
- #include <iterator>
- #include <list>
- int josephus(int num_students, int start_index, int steps)
- {
- std::list<int> students;
- for (auto i = 1; i <= num_students; ++i)
- {
- students.push_back(i);
- }
- std::list<int>::iterator it = students.begin();
- for (auto i = 1; i < start_index; ++i)
- {
- ++it;
- if (it == students.end())
- {
- it = students.begin();
- }
- }
- int countdown = num_students - 1;
- while (countdown--)
- {
- for (auto i = 0; i < steps; ++i)
- {
- ++it;
- if (it == students.end())
- {
- it = students.begin();
- }
- }
- if (it != students.begin())
- {
- it = students.erase(it);
- --it;
- }
- else
- {
- students.erase(it);
- it = students.end();
- --it;
- }
- }
- return *it;
- }
- int main() {
- int num_tests;
- std::cin >> num_tests;
- while (num_tests--)
- {
- int num_students; // formerly n
- int start_index; //formerly m
- int steps; //formerly o
- std::cin >> num_students >> start_index >> steps;
- std::cout << josephus(num_students, start_index, steps) << 'n';
- }
- }
- #include <iostream>
- int josephus(int num_students, int steps) {
- if (num_students == 1)
- {
- return 1;
- }
- else
- {
- /* The position returned by josephus(n - 1, k) is adjusted because the
- recursive call josephus(n - 1, k) considers the original position
- k % n + 1 as position 1 */
- return (josephus(num_students - 1, steps) + steps - 1) % num_students + 1;
- }
- }
- int main() {
- int num_tests;
- std::cin >> num_tests;
- while (num_tests--)
- {
- int num_students; // formerly n
- int start_index; //formerly m
- int steps; //formerly o
- std::cin >> num_students >> start_index >> steps;
- int answer = josephus(num_students, steps);
- answer = (answer + start_index) % num_students;
- if (answer != 0) {
- std::cout << answer << 'n';
- }
- else
- {
- std::cout << num_students << 'n';
- }
- }
- }
Add Comment
Please, Sign In to add comment