HDU1698 - Just a Hook (线段树 区间更新)

HDU1698 - Just a Hook (线段树 区间更新)


题目链接

思路

线段树的应用,区间更新(不用更新到底,更新到终止节点就行,查询时再将所涉及的节点信息push_down下来),颜色的数量用一个数组记录下来就行

代码

#include 
#include 
#include 
#include 
#define lson tree[root].ls
#define rson tree[root].rs

using namespace std;
const int maxn = 100000;
struct node
{
    int l, r;
    int ls, rs;
    int sta[4];
    int up;
} tree[maxn*2+100];
int nCount = 1;

void build(int root, int l, int r)
{
    tree[root].l = l;
    tree[root].r = r;
    if(l==r)
    {
        tree[root].sta[1] = 1;
        tree[root].sta[2] = 0;
        tree[root].sta[3] = 0;
        tree[root].up = 0;
        lson = 0;
        rson = 0;
    }
    else
    {
        int mid = (l+r)/2;
        lson = ++nCount;
        build(lson, l, mid);
        rson = ++nCount;
        build(rson, mid+1, r);
        for(int i=1; i<=3; i++)
            tree[root].sta[i] = tree[lson].sta[i] + tree[rson].sta[i];
        tree[root].up = 0;
    }
}
void push_down(int root)
{
    if(!tree[root].up) return;
    for(int i=1; i<=3; i++)
        tree[root].sta[i] = 0;
    tree[root].sta[tree[root].up] = (tree[root].r-tree[root].l+1);
    tree[lson].up = tree[rson].up = tree[root].up;
    tree[root].up = 0;
}
void update(int root, int l, int r, int up)
{
    if(tree[root].l==l && tree[root].r==r)
    {
        tree[root].up = up;
    }
    else
    {
        push_down(root);

        int mid = (tree[root].l+tree[root].r)/2;
        if(r<=mid) update(lson, l, r, up);
        else if(l>=(mid+1)) update(rson, l, r, up);
        else
        {
            update(lson, l, mid, up);
            update(rson, mid+1, r, up);
        }
        push_down(lson);
        push_down(rson);
        for(int i=1; i<=3; i++)
            tree[root].sta[i] = tree[lson].sta[i] + tree[rson].sta[i];
    }
}
void query(int root, int l, int r, int* ans)
{
    push_down(root);
    if(tree[root].l==l && tree[root].r==r)
    {
        for(int i=1; i<=3; i++)
            ans[i] += tree[root].sta[i];
    }
    else
    {
        int mid = (tree[root].l+tree[root].r)/2;
        if(r<=mid) query(lson, l, r, ans);
        else if(l>=(mid+1)) query(rson, l, r, ans);
        else
        {
            query(lson, l, mid, ans);
            query(rson, mid+1, r, ans);
        }
    }
}
int main()
{
    int t, n, q, tt=1;
    int x, y, z;
    int ans[4], sum;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d%d", &n, &q);
        nCount = 1;
        build(1, 1, n);
        for(int i=0; iscanf("%d%d%d", &x, &y, &z);
            update(1, x, y, z);
        }
        memset(ans, 0, sizeof(ans));
        query(1, 1, n, ans);
        sum = 0;
        for(int i=1; i<=3; i++)
            sum += ans[i]*(i);
        printf("Case %d: The total value of the hook is %d.\n", tt++, sum);
    }
    return 0;
}

你可能感兴趣的:(HDU,线段树)