D - Just a Hook

题目链接:https://cn.vjudge.net/contest/269834#problem/D

题目大意:刚开始给你n个点,每个点的价值是1,然后会区间更新价值,询问最后总的价值是多少。

题解:lazy算法。

代码:

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

struct node
{
    int l,r,num;
    int lazy;
} s[2000000];

int h[2000000];

void creat(int t,int l,int r)//建树
{
    int mid=(l+r)>>1;
    if(l==r)
    {
        s[t].l=l;
        s[t].r=r;
        s[t].lazy=1;
        return ;
    }
    s[t].l=l;
    s[t].r=r;
    s[t].lazy=1;
    creat(t*2,l,mid);
    creat(t*2+1,mid+1,r);
}

void addre(int t,int l,int r,int e)//区间更新
{
    int mid=(s[t].l+s[t].r)>>1;
    if(s[t].l==l&&s[t].r==r)
    {
        s[t].lazy=e;
        return ;
    }
    if(s[t].lazy!=0)
    {
        s[t*2+1].lazy=s[t].lazy;
        s[t*2].lazy=s[t].lazy;
        s[t].lazy=0;
    }
    if(mid>=r)
    {

        addre(t*2,l,r,e);
    }
    else if(mid<l)
    {

        addre(t*2+1,l,r,e);
    }
    else
    {
        addre(t*2,l,mid,e);
        addre(t*2+1,mid+1,r,e);
    }
}

int query(int t)//查询总价值
{
    if(s[t].lazy==0)
    {
        return query(t*2)+query(t*2+1);
    }
    else
        return (s[t].r-s[t].l+1)*s[t].lazy;
}

int main()
{
    int T;
    int a,b,c,d,e,mm=0;
    scanf("%d",&T);
    while(T--)
    {
        ++mm;
        scanf("%d %d",&a,&b);
        creat(1,1,a);
        for(int i=1; i<=b; i++)
        {
            scanf("%d %d %d",&c,&d,&e);
            addre(1,c,d,e);
        }
        printf("Case %d: The total value of the hook is %d.\n",mm,query(1));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/The_city_of_the__sky/article/details/84101289