cf 949B A Leapfrog in the Array

3 篇文章 0 订阅

一 原题

B. A Leapfrog in the Array
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.

Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows:

You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.

Input

The first line contains two integers n and q (1 ≤ n ≤ 10181 ≤ q ≤ 200 000), the number of elements in the array and the number of queries for which it is needed to find the answer.

Next q lines contain integers xi (1 ≤ xi ≤ n), the indices of cells for which it is necessary to output their content after Dima's algorithm finishes.

Output

For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.

Examples
input
Copy
4 3
2
3
4
output
3
2
4
input
Copy
13 4
10
5
4
8
output
13
3
8
9
Note

The first example is shown in the picture.

In the second example the final array is [1, 12, 2, 8, 3, 11, 4, 9, 5, 13, 6, 10, 7].

二 分析

题意:把1-n填入一个数组中,x放在下标2x-1处(下标从1开始),这样初始时所有偶数下标处都是空的。每次操作把最右的一个数字放到它左边的第一个空格中,直到数组下标1-n中没有空格。然后完成q个查询,每次查询给一个1-n之间的数y,输出最后数组中下标y处的数字。n范围1-1e18,q不超过2e5。

分析:对于一个数x,他第i次向前移动的格数记为a_i,那么a_1=2*(n-x)+1,a_i+1=2*a_i。那么任意数字的移动次数都是lgn级别的。查询x为奇数时,这个下标上的数字是从未移动的。如果是偶数,因为空格都是从右向左填的,那么x下标处的数落位时,前方有x/2个数,它的右侧有连续的(n-x/2-1)个数,因此可以判断出它移动前的位置,如果某一次移动了奇数格,那么就是这个数的第一次移动,它的值也就确定了。复杂度O(q*lgn)。

三 代码

/*
AUTHOR: maxkibble
LANG: c++ 17
PROB: cf 949B
*/

#include <cstdio>

#define LL long long

LL n;

LL f(LL x) {
    if (x % 2 == 1) return (x + 1) >> 1;
    LL step = n - (x >> 1);
    if (step & 1) return (x + step + 1) >> 1;
    else return f(x + step);
}

int main() {
    int q;
    scanf("%lld%d", &n, &q);
    LL x;
    while (q--) {
        scanf("%lld", &x);
        printf("%lld\n", f(x));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值