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.
#include <cstdio> #include <cmath> #include <cctype> #include <iostream> #include <cstring> #include <algorithm> #include <string> #include <stack> #include <vector> #include <map> #include <set> using namespace std; typedef long long LL; LL now = 0,n,l,r; LL sq[10000000] = {0}; void divide(LL n){ if (n == 1 || n == 0){ now ++; sq[now] = n; return; } divide(n/2); int nowi = now; divide(n%2); for (int i=now+1;i<=now+nowi;i++){ sq[i] = sq[i-now]; } now = now + nowi; } LL f(LL n){ if (n == 1 || n == 0){ return 1; } else return 2*f(n/2) + f(n % 2); } LL calc(LL l,LL r,LL n){ LL half = f(n/2); if (l > r) return 0; if (n == 1){ return 1; } if (r <= half){ return calc(l,r,n/2); } // r > half if (r == half + 1){ return calc(l,half,n/2) + (n % 2); } // r > half + 1 if (l > half){ if (l == half + 1){ return calc(1,r-half-1,n/2) + (n % 2); } else { return calc(l-half-1,r-half-1,n/2); } } else { // l <= half return calc(l,half,n/2) + calc(1,r-half-1,n/2) + (n % 2); } } int main() { // freopen("test.in","r",stdin); ios::sync_with_stdio(false); cin >> n >> l >> r; if (n == 0) { cout << 0; return 0; } cout << calc(l,r,n); // LL ans = 0; // for (int i=l;i<=r;i++){ // if (sq[i] == 1){ // ans ++; // } // } // cout << ans; // for (int i=1;i<=now;i++){ // cout << sq[i]; // } return 0; }