diff --git a/Josephus Problem I.cpp b/Josephus Problem I.cpp new file mode 100644 index 0000000..c03245b --- /dev/null +++ b/Josephus Problem I.cpp @@ -0,0 +1,41 @@ + +#include +using namespace std; +class Node{ +public: + int data ; + Node* next; + Node* prev; + Node(int val){ + data =val; + next= nullptr; + prev = nullptr; + } +}; + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n; + cin>>n; + Node* temp=new Node(1); + Node* first= temp; + for(int i=2;i<=n;i++){ + Node* prev = temp; + temp = new Node(i); + temp->prev = prev; + prev->next = temp; + } + temp->next= first; + first->prev= temp; + first=first->next; + while(first->next->data!=first->data && first->prev->data != first->data){ + cout<data<<" "; + Node* prev = first->prev; + prev->next = first->next; + first->next->prev = prev; + first= first->next->next; + } + cout<data; + return 0; +} \ No newline at end of file diff --git a/Josephus Problem II.cpp b/Josephus Problem II.cpp new file mode 100644 index 0000000..07b75a9 --- /dev/null +++ b/Josephus Problem II.cpp @@ -0,0 +1,24 @@ +#include +#include +using namespace __gnu_pbds; +using namespace std; + +typedef tree,rb_tree_tag, tree_order_statistics_node_update> indexed_set; +#define int long long +#define endl '\n' + +signed main(){ + ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); + indexed_set s; + int n,k; cin>>n>>k; + for (int i = 1; i <= n; i++) + s.insert(i); + + int ind = k%n; + while(n--) { + auto y = s.find_by_order(ind); + cout<<*y<<' '; + s.erase(y); + if (n) ind = (ind%n + k)%n; + } +} \ No newline at end of file