递推解决约瑟夫环问题


  1. #include <iostream>  
  2. #include <list>  
  3. using std::cout;  
  4. using std::endl;  
  5. using std::cin;  
  6. using std::list;  
  7.    
  8. int main()  
  9. {  
  10.     int total  = 0;  
  11.     cout << "Please input total number of people : ";  
  12.     cin >> total;  
  13.    
  14.     int number = 0;  
  15.     cout << "Please input selected number : ";  
  16.     cin >> number;  
  17.    
  18.     /* If number = 3 
  19.      * f(1) = 0 
  20.      * f(2) = 1 = (f(1) + 3) % 2 
  21.      * f(3) = 1 = (f(2) + 3) % 3 
  22.      * f(4) = 0 = (f(3) + 3) % 4 
  23.      * f(5) = 3 = (f(4) + 3) % 5 
  24.      * ... 
  25.      * f(n) = x = (f(n-1) + 3) % n 
  26.      * */  
  27.    
  28.     int last = 0; // f(1) = 0  
  29.     for(int i = 2; i <= total; ++i)  
  30.     {  
  31.         last = (last + number) % i;  
  32.     }  
  33.     cout << "The last one is : " << last + 1 << endl;  
  34.    
  35.     return 0;  
  36. }  

猜你喜欢

转载自blog.csdn.net/qq_38931949/article/details/79290379