Just a Hook (线段树)

  给你n个数(初始时每个数的值为1),m个操作,每个操作把区间[l,r]里的数更新为c,问最后这n个数的和是多少。

区域更新用懒惰标记

#include<bits/stdc++.h>
using namespace std;
#define N 110000
#define lson L,m,pos<<1
#define rson m+1,R,pos<<1|1
#define mid  m=(L+R)>>1
int sum[N<<2];
int col[N<<2];

void up(int pos)
{
    sum[pos]=sum[pos<<1]+sum[pos<<1|1];
}
void build(int L,int R,int pos)
{
    col[pos]=0;
    if(L==R)
      {
        sum[pos]=1;
        return ;
      }
    int mid;
    build(lson);
    build(rson);
    up(pos);
}

void down(int pos,int m)
{
    if(col[pos])
    {
        col[pos<<1]=col[pos<<1|1]=col[pos];
        sum[pos<<1]=(m-(m>>1))*col[pos];
        sum[pos<<1|1]=(m>>1)*col[pos];
        col[pos]=0;
    }
}
void update(int l,int r,int v,int L,int R,int pos)
{
    if(l<=L&&r>=R)
    {
        col[pos]=v;
        sum[pos]=v*(R-L+1);
        return ;
    }
    down(pos,R-L+1);
    int mid;
    if(l<=m)update(l,r,v,lson);
    if(r>m) update(l,r,v,rson);
    up(pos);
}

int main() {
       int T , n , m;
       scanf("%d",&T);
       for (int cas = 1 ; cas <= T ; cas ++) {
              scanf("%d%d",&n,&m);
              build(1 , n , 1);
              while (m --) {
                     int a , b , c;
                     scanf("%d%d%d",&a,&b,&c);
                     update(a , b , c , 1 , n , 1);
              }
              printf("Case %d: The total value of the hook is %d.
",cas , sum[1]);
       }
       return 0;
}
原文地址:https://www.cnblogs.com/bxd123/p/10461375.html