HDU 4893(Wow! Such Sequence!)

题意:略;

思路:挺水的一道线段树题,刚开始没注意到如果一个数是斐波那契数,离它最近的斐波那契数是它自己,挺囧的、、

知道这个性质之后,就再每个节点加多一个标记,是否节点所代表的区间都是斐波那契数,然后下次操作的时候

如果当前区间全是斐波那契数的话就可以直接返回了。

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

typedef long long LL;
const int N = 100005;
LL sum[N << 2];
bool ok[N << 2];
set S;
set::iterator iter;

LL myAbs(LL a) {
    return a < 0 ? -a : a;
}

void modify(int i, int l, int r, int loc, int add) {
    if(l > loc || loc > r)
        return ;
    if(l == r) {
        sum[i] += add;
        if(S.find(sum[i]) != S.end()) {
            ok[i] = true;
        } else {
            ok[i] = false;
        }
        return ;
    }
    int mid = l + r >> 1;
    modify(i << 1, l, mid, loc, add);
    modify(i << 1 | 1, mid + 1, r, loc, add);
    sum[i] = sum[i << 1] + sum[i << 1 | 1];
    ok[i] = (ok[i << 1] & ok[i << 1 | 1]);
}

void change(int i, int l, int r, int ql, int qr) {
    if(l > qr || ql > r)
        return ;
    if(ok[i])
        return ;
    if(l == r) {
        if(sum[i] <= 0) {
            sum[i] += -sum[i] + 1;
        } else {
            iter = S.lower_bound(sum[i]);
            LL right = *iter;
            iter--;
            LL left = *iter;
            if(myAbs(sum[i] - left) <= myAbs(sum[i] - right)) {
                sum[i] -= myAbs(sum[i] - left);
            } else {
                sum[i] += myAbs(sum[i] - right);
            }
        }
        ok[i] = true;
        return ;
    }
    int mid = l + r >> 1;
    change(i << 1, l, mid, ql, qr);
    change(i << 1 | 1, mid + 1, r, ql, qr);
    sum[i] = sum[i << 1] + sum[i << 1 | 1];
    ok[i] = (ok[i << 1] & ok[i << 1 | 1]);
}

LL query(int i, int l, int r, int ql, int qr) {
    if(l > qr || ql > r)
        return 0ll;
    if(l >= ql && r <= qr)
        return sum[i];
    int mid = l + r >> 1;
    LL x = query(i << 1, l, mid, ql, qr);
    LL y = query(i << 1 | 1, mid + 1, r, ql, qr);
    return x + y;
}

int main() {
    LL fib[88];
    int n, nq;
    fib[0] = fib[1] = 1;
    S.insert(1);
    for(int i = 2; i <= 80; i++) {
        fib[i] = fib[i - 1] + fib[i - 2];
        S.insert(fib[i]);
    }
    while(cin >> n >> nq) {
        memset(ok, false, sizeof ok);
        memset(sum, 0, sizeof sum);
        while(nq--) {
            int ord, l, r;
            scanf("%d%d%d", &ord, &l, &r);
            if(ord == 1) {
                modify(1, 1, n, l, r);
            } else if(ord == 2) {
                printf("%I64d\n", query(1, 1, n, l, r));
            } else {
                change(1, 1, n, l, r);
            }
        }
    }
    return 0;
}


你可能感兴趣的:(ACM,数据结构)