CodeForces768B:Code For 1 (分治)

Posted ---学习ing---

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForces768B:Code For 1 (分治)相关的知识,希望对你有一定的参考价值。

Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon‘s place as maester of Castle Black. Jon agrees to Sam‘s proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility.

Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that x > 1, from the list and insert at the same position 技术分享图片技术分享图片技术分享图片 sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.

Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?

Input

The first line contains three integers nlr (0 ≤ n < 2500 ≤ r - l ≤ 105r ≥ 1, l ≥ 1) – initial element and the range l to r.

It is guaranteed that r is not greater than the length of the final list.

Output

Output the total number of 1s in the range l to r in the final sequence.

Examples

Input
7 2 5
Output
4
Input
10 3 10
Output
5

Note

Consider first example:

技术分享图片

Elements on positions from 2-nd to 5-th in list is [1, 1, 1, 1]. The number of ones is 4.

For the second example:

技术分享图片

Elements on positions from 3-rd to 10-th in list is [1, 1, 1, 0, 1, 0, 1, 0]. The number of ones is 5.

 

题意:一开始有一个数N,每次把所有大于1的数变为x/2,x%2,x/2。知道不能操作。样例如题。

思路:找规律我们得知,最后的01串有很多的对称性。首先推出最后一层有num=2^(lg2(N)+1) -1个数,并且以x=(num+1)/2为对称轴,所以如果在对称轴的右边,我们可以把它对称到x轴的左边。   然后把对称轴左边的区间[1,x]又看成一个整体,它又以x2=(x+1)/2为对称轴,如果在x2右边,又把它对称到x2左边.....一直对称下去,直到把它对称到一个对称轴上。而我们可以求出对称轴上对应的数的值,就是N的二进制对应的数。

          比如10的二进制表示为10(ten)=1010(two)。10=1(1)+0(2)+1(4)+0(8),(括号里的是最后一层的对称轴位置,也是最后一层二进制对应位置的结果)。

(ps:也可以用分形来做。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=100010;
ll find(ll x){
    ll y=log2(x);
    if(1LL<<y==x) return y;
    return find((1LL<<(y+1))-x);
}
int main()
{
    ll N,L,R,ans=0,Bit;
    cin>>N>>L>>R;
    Bit=log2(N);
    for(ll i=L;i<=R;i++)
        ans+=(N>>(Bit-find(i)))&1LL;
    cout<<ans<<endl;
    return 0;
}

 

以上是关于CodeForces768B:Code For 1 (分治)的主要内容,如果未能解决你的问题,请参考以下文章

CF768B Code For 1 题解 分治

http://codeforces.com/problemset/problem/768/B B. Code For 1

CodeForces-768B-Code For 1+DFS类似线段树思想

Codeforces768B-Code For 1-类似线段树-枚举+单点更新or区间更新

Educational Codeforces Round 69 (Rated for Div. 2) E. Culture Code

Codeforces Round #584 - Dasha Code Championship - Elimination Round (rated, open for everyone, Div.