ZOJ 2072 K-Recursive Survival

https://vjudge.net/contest/67836#problem/K

 

n people numbered 1 to n around a circle, we eliminate every second remaining person until only one survives. Define a function J(n), represents the survivor's original number in the circle. For example, J(2)=1, J(10)=5. Now, please calculate this nested function: J(J(J(..J(n)..)))


Input

There are multiple test cases, each with two positive numbers in one line.

The first number represents the number of the people in original cirlcle, the second one represents the times of the function nested.

All the numbers in input file will be less than 2^63-1.


Output

output the result in one line per test case.


Sample Input

2 1
10 1
10 2


Smaple Output

1
5
3

 时间复杂度:$O(M * log(N))$

题解:约瑟夫环, 递归

代码:

#include <bits/stdc++.h>
using namespace std;

long long J(long long n) {
    if(n == 0 || n == 1)
        return 1;
    else if(n % 2 == 0)
        return 2 * J(n / 2) - 1;
    else
        return 2 * J(n / 2) + 1;
}

int main() {
    long long N, M;
    while(~scanf("%lld%lld", &N, &M)) {
        for(long long i = 0; i < M; i ++) {
            long long c;
            c = J(N);
            if(c == N) break;
            N = c;
        }
        printf("%lld\n", N);
    }
    return 0;
}

  

posted @ 2018-08-24 13:06  丧心病狂工科女  阅读(204)  评论(0编辑  收藏  举报