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, 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)/~

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值