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 ≤ 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.
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
Copy
3 2 4
input
Copy
13 4 10 5 4 8
output
Copy
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,从1到n在数组中是固定的,后续我们需要进行前移的操作,使得数组从1到n先填满数组,在这个过程中仔细想一下不难想出1到n中的奇数位是不变的(都是n/2+1)。所以这道题我们只需要对偶数位进行特殊判断就好了。
打表找规律如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5;
int num[maxn];
int main()
{
for(int i=1;i<=20;++i)
{
memset(num,0,sizeof(num));
for(int j=1;j<=i;++j)
{
num[2*j-1]=j;
}
int w=2*i-2,e=2*i-1;
while(w)
{
if(!num[e]) e--;
num[w]=num[e--];
w-=2;
}
for(int j=1;j<=i;++j)
printf("%d ",num[j]);
cout<<endl;
}
return 0;
}
观察箭头上面的两组数据,能够发现上面的1是下面的2-1,7是下面的8-1........6是下面的7-1.
对于任意行,这个规律都是成立的。
对于第i行的第j个偶数x,我们要找第i-1行x-1在哪个位置,我首先想到是j-2,可发现如果是j是2的时候j-2=0就不对了,下面要解决的就是这样一个问题。
每向上移动一层,当前数字减少一,直到我们移动到的层数所对应的数字为奇数,计算就结束了。(因为奇数对应的数字可以计算)。
然而一步一步移动(比如从第13层的8到12层的6到11层的4到10层的2到8层的8......)
就发现从i层的x到j层的y,在这个过程中j=y=i-x/2。
直接while循环就好了。
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n,k,x;
cin>>n>>k;
while(k--)
{
scanf("%lld",&x);
if(x&1)
printf("%lld\n",x/2+1);
else
{
long long m=n;
while(x%2==0)
{
x=m-x/2;
m=x;
}
printf("%lld\n",n-x+x/2+1);
}
}
return 0;
}