Codeforces 949B A Leapfrog in the Array(数学,规律)

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].

http://codeforces.com/problemset/problem/949/B

题目:一开始给你一个1到n全部放在数组奇数为的数组,然后每次数组最后的一个数放入最近的空位里,然后一直循环操作直到数组没有空位。

题解:

这题可以说是规律题,我发现的规律是后面每个数第i次移动的距离都是k*2^(i-1),这里的k是指数字的原始位置m与2*n之间的距离。因此,当每个数字最终运动到小于n时就停止。所以有公式最终位置x=m-(2*n-m)(2^t-1)<n(t是运动次数)。因此我们反推公式,可以得到m=2*n-(2*n-x)/2^t;(这里(2*n-x)/2^t)必须处出来是整数并且被2除余1),然后用m在推导出m出数字的值就行了公式不难 看出是ans=(m+1)/2。

@```C++@
#include<stdio.h>
#include<iostream>
using namespace std;
typedef long long ll;
ll fun(ll x,ll n)
{
	ll temp=2*n-x;
	while((temp&1)==0)
	{
		temp>>=1;
//		cout<<temp<<endl;
	}
	return (2*n-temp+1)/2;
}
int main()
{
	long long n;
	int q;
	scanf("%lld%d",&n,&q);
	while(q--)
	{
		long long a;
		scanf("%lld",&a);
		if(a&1)
		{
			printf("%lld\n",(a+1)/2);
		}
		else
		{
			printf("%lld\n",fun(a,n));
		}
	}
}
@```@

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值