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, 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
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%2和n/2,n/2.直到只剩1和0结束。结束了之后,给你一个区间,问这个区间里有多少个1。用线段树可以解决。。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define ll long long
using namespace std;
ll n;
ll l,r;
ll query(ll L,ll R,ll num)
{
if(R<l||L>r||num==0) return 0;//如果界限不对或者是0的话,就直接返回0。
if(L>=l&&R<=r) return num;//如果现在的区域正好被所求区域包围,返回这个num就好了,不用继续发往下分了,反正1的个数加起来就是这个num。
ll mid=(L+R)/2;
ll a=query(L,mid-1,num/2);//左区域
ll b=query(mid+1,R,num/2);//右区域
ll c=query(mid,mid,num%2);//中间
return a+b+c;
}
int main()
{
while(scanf("%lld%lld%lld",&n,&l,&r)!=EOF)
{
ll cnt=n;
ll len=1;
ll ant=2;
while(cnt>1)//求由数字n按着题意分下去区域有多长。
{
len+=ant;
cnt/=2;
ant*=2;
}
printf("%lld\n",query(1,len,n));
}
return 0;
}
线段树不得不说特别有用,好好看看。
努力加油a啊,(o)/~