UVA10774 Repeated Josephus【约瑟夫环+位运算】

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

问题链接UVA10774 Repeated Josephus
问题简述:(略)
问题分析
    简单约瑟夫环问题,给代码,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA10774 Repeated Josephus */

#include <bits/stdc++.h>

using namespace std;

int find(int n)
{
    int cnt = 0;
    while(n) cnt++, n >>= 1;
    return cnt;
}

int jos(int n)
{
    int len = find(n);
    n ^= (1 << (len - 1));
    n <<= 1;
    n |= 1;
    return n;
}

int main()
{
    int t, caseno = 0, n, survivor;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);

        int cnt = 0;
        for(;;) {
            cnt++;
            if((survivor = jos(n)) == n) break;
            n = survivor;
        }

        printf("Case %d: %d %d\n", ++caseno, cnt - 1, n);
    }

    return 0;
}
UVA10774 Repeated Josephus【约瑟夫环+位运算】UVA10774 Repeated Josephus【约瑟夫环+位运算】 海岛Blog 发布了2090 篇原创文章 · 获赞 2293 · 访问量 252万+ 他的留言板 关注
上一篇:2020牛客暑期多校训练营(第六场) Josephus Transform


下一篇:Scala之函数