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 n, l, r (0 ≤ n < 250
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
Input7 2 5Output
4Input
10 3 10Output
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 (分治)