Tuesday, May 5, 2020

POJ.1012 Joseph

1.Problem
http://poj.org/problem?id=1012

2.Idea
https://en.wikipedia.org/wiki/Josephus_problem

3.Source
 int Joseph[15];  
 int k;  
 int main()  
 {  
      while (scanf("%d", &k) && k) {  
           if (Joseph[k]) {  
                printf("%d\n", Joseph[k]);  
                continue;  
           }  
           int n = 2 * k, m = 1;  
           int flag[30] = { 0 };  
           for (int i = 1; i <= k; i++) {  
                flag[i] = (flag[i - 1] + m - 1) % (n - i + 1);  
                if (flag[i] < k) {  
                     i = 0;  
                     m++;  
                }  
           }  
           Joseph[k] = m;  
           printf("%d\n", m);  
      }  
      return 0;  
 }  

No comments:

Post a Comment