一 原題
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.
The first line contains two integers n and q (1 ≤ n ≤ 1018, 1 ≤ 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.
For each of q queries output one integer number, the value that will appear in the corresponding array cell after Dima's algorithm finishes.
4 3 2 3 4
3 2 4
13 4 10 5 4 8
13 3 8 9
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;
}