HDU 4348 To the moon

题目要求有一下几个操作:区间加个数(此时时间计数+1),查询区间和,查询历史区间和,时间回退到过去某个时间。

可持久化线段树,用T[i]表示时间为i的时候的树根;

由于整一个更新只有单一的加法,所以我们不必利用lazy标记,我们用一个标记来记录当前节点的整段区间被累加了多少,当询问的时候我们在从根节点走到目标结点的过程中不断累加所经过节点上的标记值,这样就提高了每棵树的共享信息


#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
const int N = 100005;
const int M = N*40;
int tot,n,q;
ll sum[M], flag[M];
int T[N], ls[M], rs[M];
void pushup(int rt){
    sum[rt] = sum[ls[rt]] + sum[rs[rt]];
}
void build(int l, int r, int &rt){
    rt = tot ++;
    if(l == r){
        scanf("%I64d",&sum[rt]);
        return ;
    }
    int mid = (l+r)>>1;
    build(l, mid, ls[rt]);
    build(mid+1, r, rs[rt]);
    pushup(rt);
}
int newnode(int rt, int l, int r, ll val){
    int newroot = tot ++;
    ls[newroot] = ls[rt];
    rs[newroot] = rs[rt];
    flag[newroot] = flag[rt] + val;
    sum[newroot] = sum[rt] + (r-l+1)*val;
    return newroot;
}
int update(int rt, int l, int r, int x, int y, ll val){
    if(x<=l && y>=r){
        return newnode(rt, l, r, val);
    }
    if(r < x || l > y)return rt;
    int mid = (l+r)>>1, newroot = tot++;
    flag[newroot] = flag[rt];
    sum[newroot] = sum[rt] + (min(r,y) - max(l,x) + 1) * val;
    ls[newroot] = update(ls[rt], l, mid, x, y, val);
    rs[newroot] = update(rs[rt], mid+1, r, x, y, val);
    return newroot;
}
ll query(int rt, int l, int r, int x, int y, ll val){
	if(l >= x && r <= y){
		return sum[rt] + (r-l+1) * val;
	}
	if(r < x || l > y)return 0;
	int mid = (l+r)>>1;
	return query(ls[rt], l, mid, x, y, val+flag[rt]) + query(rs[rt], mid+1, r, x, y, val+flag[rt]);
}
int main(){
    //freopen("in.txt","r",stdin);
    char str[5];
	int l,r,k;
	while(~scanf("%d%d", &n, &q)){
		tot = 0;
		build(1, n, T[0]);
		int cot = 0;
		for(int i = 0; i < q; i++){
			scanf("%s",str);
			if(str[0] == 'C'){
				scanf("%d%d%d", &l, &r, &k);
				++cot;
				T[cot] = update(T[cot-1],1,n,l,r,k);
			}
			else if(str[0] == 'Q'){
				scanf("%d%d", &l, &r);
				printf("%I64d\n",query(T[cot],1,n,l,r,0));
			}
			else if(str[0] == 'H'){
				scanf("%d%d%d", &l, &r, &k);
				printf("%I64d\n",query(T[k],1,n,l,r,0));
			}
			else {
				scanf("%d",&k);
				cot = k;
			}
		}
	}
	return 0;
}


你可能感兴趣的:(HDU,主席树)