Codeforces 949B A Leapfrog in the Array(数学,规律)
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:
![](http://codeforces.com/predownloaded/1e/83/1e838f4fb99d933b7259fbfe5b8722990c08d718.png)
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].
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)); } } } @```@