线段树区间更新(2)(lazy)(区间都变为v)(序号从1开始)(O(logn))模板(hdu1698)

来源:互联网 发布:御剑江湖进阶数据 编辑:程序博客网 时间:2024/05/29 19:40

线段树区间更新模板

AC code

#include <iostream>#include <string>#include<cstring>#include <stdio.h>#include <cmath>#include <algorithm>#include <vector>#define y1 yy1#define y2 yy2const int maxn = 1 << 18;const int MOD = 1e9 + 7;const int INF = 0x3f3f3f3f;using namespace std;typedef long long LL;int setv[maxn];int sumv[maxn];int n,q;int y1,y2,v;void init(int _n) {       n = 1;       while(n < _n)          n *= 2; }void pushdown(int o){    int lc = o*2,rc = o*2+1;    if(setv[o] >= 0)    {        setv[lc] = setv[rc] = setv[o];        setv[o] = -1;    }}void maintain(int o,int L,int R){    int lc = o*2,rc = o*2+1;    sumv[o] = 0;    if(setv[o] >= 0)    sumv[o] = (R-L+1)*setv[o];    else {        if(L < R)        sumv[o] = sumv[lc] +sumv[rc];    }}   void update(int o, int L, int R){    int lc = o*2,rc = o*2+1;    if(L >= y1 && R <= y2)        setv[o] = v;    else {        pushdown(o);        int M = L + (R-L)/2;        if(y1 <= M)   update(lc,L,M);   else maintain(lc,L,M);        if(y2 > M)    update(rc,M+1,R); else maintain(rc,M+1,R);    }    maintain(o,L,R);}LL Query(int o, int L,int R){    if(y1 > R || y2 < L) return 0;    int lc = o*2,rc = o*2+1;    if(setv[o] >= 0)        return setv[o]*(R-L+1);    else if(L >= y1 && R <= y2)        return sumv[o];    else {        int M = L + (R - L)/2;                          return Query(lc,L,M) + Query(rc,M+1,R);        }}int main()              {    int T;    cin >> T;    int t = T;    while(t--)   {    cin >> n >> q;    int n0 = n;    init(n);    memset(setv,-1,sizeof(setv));    memset(sumv,0,sizeof(sumv));    for(int i = 1; i <= n0; i++)  {         v = 1;    y1 = y2 = i;    update(1,1,n);  }  while(q--)   {    scanf("%d%d%d",&y1,&y2,&v);    update(1,1,n);  }  y1 = 1; y2 = n;   printf("Case %d: The total value of the hook is %I64d.\n",T-t,Query(1,1,n));}   return 0; }