Josephus Problem
N people have decided to elect a leader by arranging themselves in a
circle and eliminating every M th person around the circle, closing
ranks as each person drops out. The problem is to find out which person
will be the last one remaining ( a mathematically inclined potential
leader will figure out ahead of time which position in the circle to take).
From Algorithms in C++.
*/
#include#include using namespace std; struct node { int item; node *next; node( int n, node *t ) { item = n; next = t; } }; // typedef node *link; // Using link instead of linkk has compile error // I don't know the reason. typedef node *linkk; // int main( int argc, char *argv[] ) int main() { // int i, N = atoi(argv[1]), M = atoi(argv[2]); int i; int N = 9; // number of people int M = 5; linkk t = new node( 1, 0 ); t->next = t; linkk x = t; for ( i = 2; i <= N; ++i ) { x = ( x->next = new node(i, t) ); } while (x != x->next ) { // move the pointer M-1 times for ( i = 1; i < M; ++i ) x = x->next; // delete the next item from the list linkk temp = x->next; x->next = x->next->next; delete temp; } cout << x->item << endl; return 0; }
No comments:
Post a Comment