24h購物| | PChome| 登入
2013-07-07 18:10:07| 人氣1,460| 回應0 | 上一篇 | 下一篇

[UVA] 10774 - Repeated Josephus

推薦 0 收藏 0 轉貼0 訂閱站台

Repeated Josephus
Input: standard input
Output: standard output
Time Limit: 1 second


No, I don't want you to waste important time reading boring introduction. At first, there are n people numbered 1 to n around a circle and every second remaining person will be eliminated until only one survives. Let the number of the survivor be x. The process is then repeated with x number of people and let the survivor number is y. The process then starts with y number of people and so on. The repetition ends when the survivor is in the last position in the circle.
Example with n = 5:
After the first elimination round, the survivor is person 3. Because this is is not the last person in the circle, a new elimination round with 3 people is started.
Now person 3 survives, so we can stop.

 

Input

 

The first line in the input file is an integer representing the number of test cases. Each of the test cases follows below. Each test case consists of an integer representing n ( 0 < n ≤ 30000 ).

Output

 

For each test case, print the serial number of the case, a colon, an space, total number of repetitions (the number of times the elimination process is done after the initial elimination round with n people), an space and the position of the survivor at last. Check the sample input & output.

 

Sample Input

2

13

23403

Sample Output

Case 1: 2 7
Case 2: 8 1023

 


Problem setter: Anupam Bhattacharjee, CSE, BUET
Thanks to Adrian for alternate solution.
 

"~~ Simple matters in the world need not always be simple ~~" 

中文翻譯請去不幸狗。

題目解法:

可以用 O(n) 算出每兩個殺掉一個人的存活者,根據題目意思模擬即可。


#include <stdio.h>
int josephus(int n, int m) {
    int s = 0, i;
    for(i = 2; i <= n; i++)
        s = (s+m)%i;
    return s+1;
}
int main() {
    int testcase, cases = 0;
    int n;
    scanf("%d", &testcase);
    while(testcase--) {
        scanf("%d", &n);
        printf("Case %d: ", ++cases);
        int repeat = 0, survivor;
        while(1) {
            survivor = josephus(n, 2);
            repeat++;
            if(survivor == n)
                break;
            n = survivor;
        }
        printf("%d %d\n", repeat-1, n);
    }
    return 0;
}

台長: Morris
人氣(1,460) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][greedy] 10716 - Evil Straw Warts Live
此分類上一篇:[UVA] 10705 - The Fun Number System

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文