Codeforces 950D A Leapfrog in the Array 找规律

题目链接:A Leapfrog in the Array

题意

最初有一个长度为 2 n 1 的数组,数组的每个偶数位都是空的,数组的 2 x 1 位上的数字为 x ,然后将这个数组的最后一个数字放到数组的最后一个空着的位上,不断执行这个操作,直到数组中不再有空位为止,最终数组的长度为 n ,对于一个长度为 2 n 1 = 7 的的初始数组,操作如下:

对于一个长度为 n 的最终数组, q 次询问它的第 x 位上的数字的值。

输入

第一行为两个整数 n , q   ( 1 n 10 18 , 1 q 2 × 10 5 ) ,接下去 q 行每行一个整数 x

输出

对于每次询问,输出最终数组 x 位上的数字。

样例

输入
4 3
2
3
4
输出
3
2
4
提示
最终数组如上图所示。
输入
13 4
10
5
4
8
输出
13
3
8
9
提示
最终数组为: [ 1 , 12 2 , 8 , 3 , 11 , 4 , 9 , 5 , 13 , 6 , 10 , 7 ]

题解

对于每次询问,若 x 为奇数,则答案为 x + 1 2 ,否则将 x 位上的数字还原到原来的位置上,第 x 位上的数字,假设它左边所有的奇数位的数字都已经归位,偶数位上的数字都已经到它的后面,现在到这个位置上的数字还原,那么它左边的数字有 x 2 个,右边的数字有 n x 2 ,因此这个数字一次还原的位置为 x + n x 2 ,不断还原下去,直到 x 为奇数为止。

过题代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <algorithm>
#include <functional>
#include <iomanip>
using namespace std;

#define LL long long
LL n, q;
LL x, Index;

int main() {
    #ifdef LOCAL
        freopen("test.txt", "r", stdin);
//    freopen("out.txt", "w", stdout);
    #endif // LOCAL
    ios::sync_with_stdio(false);

    while(scanf("%I64d%I64d", &n, &q) != EOF) {
        while(q--) {
            scanf("%I64d", &x);
            while(x % 2 == 0) {
                x += n - x / 2;
            }
            printf("%I64d\n", (x + 1) / 2);
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/CSDNjiangshan/article/details/81388946