Created
May 19, 2012 16:30
-
-
Save opilar/2731406 to your computer and use it in GitHub Desktop.
118.acmp | Josephus problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
// ifstream cin ("input.txt"); | |
// ofstream cout ("output.txt"); | |
struct elem | |
{ | |
int n; | |
elem* next; | |
} *nextfree; | |
void MakeFirst (elem** head, int n) | |
{ | |
*head = nextfree++; | |
(*head)->n = n; | |
(*head)->next = *head; | |
} | |
void locate (int k, elem** p) | |
{ | |
for (int i = 1; i < k; i++) | |
*p = (*p)->next; | |
} | |
void insert (elem *p, int n) | |
{ | |
elem *t = nextfree++; | |
t->next = p->next; | |
p->next = t; | |
t->n = n; | |
} | |
void del (elem *p) | |
{ | |
p->next = p->next->next; | |
} | |
int main () | |
{ | |
int n, k; | |
cin >> n >> k; | |
elem *p = nextfree = new elem[n]; | |
elem *t; | |
MakeFirst(&t, n); | |
for (int i = n-1; i >= 1; i--) | |
insert (t, i); | |
for (int i = 1; i < n; i++) | |
{ | |
locate (k, &t); | |
del (t); | |
} | |
cout << t->n << endl; | |
delete []p; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment