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?
The first line contains three integers n, l, r (0 ≤ n < 250, 0 ≤ r - l ≤ 105, r ≥ 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 the total number of 1s in the range l to r in the final sequence.
7 2 5
4
10 3 10
5
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,对n一直进行x/2, x%2, x/2直到整个序列只有0和1,问在区间[l, r]中有多少个1。
思路:对于每个n的序列长度,公式为f[n] = f[n/2] * 2 + 1。则可以不断对n除2,用ans记录当前n%2是否为1,不断递归,还用到了二分的思想,见代码。
#include <iostream>
#include <cstdio>
#include <cstring>
typedef long long ll;
using namespace std;
ll ans = 0;
void slove(ll a, ll b, ll l, ll r, ll d)
{
if(a > b || l > r) return ;
ll mid = (a+b) / 2;
if(r < mid) slove(a, mid-1, l, r, d/2);
else if(l > mid) slove(mid+1, b, l, r, d/2);
else {
ans += d%2;
slove(a, mid-1, l, mid-1, d/2);
slove(mid+1, b, mid+1, r, d/2);
}
}
int main()
{
ll n, r, l;
while(cin >> n >> l >> r) {
ll p = n, s = 1;
while(p > 1) {
p /= 2;
s = s*2 + 1; // 求出最后序列长度,即为二分初始上界
}
ans = 0;
slove(1, s, l, r, n);
cout << ans << endl;
}
return 0;
}