Topic 1356: Children's games (the last remaining number in the circle) time limit: 10 seconds Memory limit: 32 Mega Special: No submission: 1073 resolution: 391 title Description: Every year children's Day, JOBDU will prepare some small gifts to visit the orphanage children, this year is also the case. HF as the senior veteran of the JOBDU, naturally also prepared some small games. Among them, there is a game like this: first, let the children surround a big circle. Then, he randomly assigned a number m, so that the number of children numbered 1 began to count. Every time the child shouted to M to sing a song, and then can be in the Gift box arbitrary selection of gifts, and no longer back to the circle, from his next friend began, continue to 1...m count off .... Go on like this .... Until the last child left, can not perform, and get Jobdu valuable "Detective Conan" Collector's Edition (limited number of seats Oh!!) ^_^). Please try to think, which one of the children will get the present? Input: Input has multiple sets of data. A row of data for each group, containing 2 integers n (0<=n<=1,000,000), M (1<=m<=1,000,000), n,m respectively the number of children (numbered 1....n-1,n) and the number of m specified by HF (as described above). If n=0, the input is ended. Output: corresponding to each set of data, output the last child to get the prize number. Sample input: 1 108 56 60 Sample output: 134
This is a question of Joseph Ring:
Solution One: Easy time-out using a linked list solution
#include <iostream> #include <stdio.h> #include <algorithm> #include <list>using namespace std; int lastremaining (unsigned int n,unsigned int m) {if (n<1| | m<1) {return-1; } unsigned int i = 0; List<int> numbers; for (int i=1;i<=n;i++) {numbers.push_back (i); } list<int>::iterator current = Numbers.begin (); while (Numbers.size () >1) {for (int i=1;i<m;i++) {current++; if (Current==numbers.end ()) {current = Numbers.begin (); }} List<int>::iterator next = ++current; if (Next==numbers.end ()) {next = Numbers.begin (); }--current; Numbers.erase (current); current = next; } return *current;} int main () {int n,m; while (scanf ("%d%d", &n,&m)!=eof&&n) {printf ("%d\n", Lastremaining (n,m)); } return 0;}
Solution 2: Formula Solution
#include <iostream> #include <stdio.h> #include <algorithm> #include <list>using namespace std; int lastremaining (unsigned int n,unsigned int m) { if (n<1| | m<1) { return-1; } int last = 0; for (int. i=2;i<=n;i++) {Last = (last+m)%i; } return last+1;} int main () { int n,m; while (scanf ("%d%d", &n,&m)!=eof&&n) { printf ("%d\n", Lastremaining (N,m)); } return 0;}
Sword refers to the offer series source-the last remaining number in the circle