1. 程式人生 > >Code For 1(線段樹思想)

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