HDU - 1698 Just a Hook (线段树区间修改+lazy标记)

#include 
using namespace std;
typedef long long ll;
struct node
{
    ll l, r, sum;
}a[400005];
ll lazy[400005];
ll num[100005];
void build(ll loc, ll l, ll r)
{
    if(l == r)
    {
        a[loc].l = l;
        a[loc].r = r;
        a[loc].sum = 1;
        return ;
    }
    else
    {
        a[loc].l = l;
        a[loc].r = r;
        ll mid = (l + r) / 2;
        build(loc * 2, l, mid);
        build(loc * 2 + 1, mid + 1, r);
        a[loc].sum = a[loc * 2].sum + a[loc * 2 + 1].sum;
    }
}
void ad(ll loc, ll x, ll y, ll p)
{
    ll l = a[loc].l, r = a[loc].r;
    if(lazy[loc] != 0)
    {
        ll aaa = lazy[loc];
        if(a[loc].l == a[loc].r){lazy[loc] = 0;}
        else {
        lazy[loc * 2] = lazy[loc * 2 + 1] = aaa;
        lazy[loc] = 0;
        ll mid = (l + r) / 2;
        a[loc * 2].sum = aaa * (mid - l + 1);
        a[loc * 2 + 1].sum = aaa * (r - mid);
        }
    }
    if(l == x && r == y)
    {
        a[loc].sum = p * (r - l + 1);
        lazy[loc] += p;
        return ;
    }
    else
    {
        ll mid = (l + r) / 2;
        if(y <= mid)
        {
            ad(loc * 2, x, y, p);
        }
        else if(x > mid)
        {
            ad(loc * 2 + 1, x, y, p);
        }
        else
        {
            ad(loc * 2, x, mid, p);
            ad(loc * 2 + 1, mid + 1, y, p);
        }
        a[loc].sum = a[loc * 2].sum + a[loc * 2 + 1].sum;
        return ;
    }
}
ll qu(ll loc, ll li, ll ri)
{
    ll l = a[loc].l, r = a[loc].r;
    if(lazy[loc] != 0)
    {
        ll aaa = lazy[loc];
        if(a[loc].l == a[loc].r){lazy[loc] = 0;}
        else {
        lazy[loc * 2] = lazy[loc * 2 + 1] = aaa;
        lazy[loc] = 0;
        ll mid = (l + r) / 2;
        a[loc * 2].sum = aaa * (mid - l + 1);
        a[loc * 2 + 1].sum = aaa * (r - mid);
        }
    }
    if(l == li && r == ri)
    {
        return a[loc].sum;
    }
    else
    {
        ll mid = (l + r) / 2;
        if(ri <= mid)
        {
            return qu(loc * 2, li, ri);
        }
        else if(mid < li)
        {
            return qu(loc * 2 + 1, li, ri);
        }
        else return qu(loc * 2, li, mid) + qu(loc * 2 + 1, mid + 1, ri);
    }
}
char s[1005];
int main()
{
    ll t, n, m, i, j, k,qwe,ca = 1;
    scanf("%lld", &t);
    while(t--)
    {
        memset(lazy, 0, sizeof(lazy));
        scanf("%lld %lld", &n, &m);
        build(1, 1 , n);
        for(k = 0; k < m; k++)
        {
            scanf("%lld %lld %lld", &i, &j, &qwe);
            ad(1, i, j, qwe);
        }
        printf("Case %lld: The total value of the hook is %lld.\n",ca++, qu(1, 1, n));
    }
    return 0;

}

 

你可能感兴趣的:(线段树区间修改)