CodeForces-768B-Code For 1+DFS类似线段树思想

Code For 1

题意:

对于一个n,可以将它分解为n/2,n%2,n/2三个数字,重复上述操作知道虽有值为1或0为止;

  求L---R区间数列的和;

思路:

首先画着画着可以发现这是一个类似线段数的结构,其长度len在每次n/2时,$len=len*2+1$;

有了长度和n就可以dfs查询区间的和了;

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
typedef long long ll;

ll len = 1;
int dfs(ll n, ll L, ll R, ll l, ll r) {
    if (L > r || R < l || n == 0) return 0;
    if (n == 1) return 1;
    ll mid = L + (R - L) / 2;
    return dfs(n / 2, L, mid - 1, l, r) + dfs(n % 2, mid, mid, l, r) + dfs(n / 2, mid + 1, R, l, r);
}
int main() {
    ll n, l, r;
    scanf("%lld%lld%lld", &n, &l, &r);
    ll N = n;
    while (N > 1) {
        len = len * 2 + 1;
        N /= 2;
    }
    printf("%d\n", dfs(n, 1, len, l, r));
    return 0;
}
View Code

 

posted @ 2018-02-24 15:40  ckxkexing  阅读(134)  评论(0编辑  收藏  举报