zoukankan      html  css  js  c++  java
  • hdu1166 线段树,点修改,区间求和

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166

    题意:中文的。求若干个区间中工人的个数。

    思路:简单线段树,点修改。只更新叶子节点,然后把信息用PushUP(int r)这个函数更新上来。

    #include<cmath>
    #include<cmath>
    #include<algorithm>
    #include<iostream>
    #include<cstdio>
    using namespace std;
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    const int maxn=55555;//最大区间长度
    int sum[maxn<<2];//节点数组,4倍长度
    void PushUP(int rt)
    {
        sum[rt]=sum[rt<<1]+sum[rt<<1|1];
    }
    void build(int l,int r,int rt)
    {
        if(l==r)
        {
            scanf("%d",&sum[rt]);
            return;
        }
        int m=(l+r)>>1;
        build(lson);
        build(rson);
        PushUP(rt);
    }
    void update(int p,int add,int l,int r,int rt)
    {//对p进行更新操作,加上add,l,r表示操作范围,rt表示当前节点
        if(l==r)
        {
            sum[rt]+=add;
            return;
        }
        int m=(l+r)>>1;
        if(p<=m) update(p,add,lson);
        else update(p,add,rson);
        PushUP(rt);
    }
    int query(int L,int R,int l,int r,int rt)
    {//[L,R]要查询的区间,[l,r]当前节点所在区间
        if(L<=l && r<=R)
           return sum[rt];
        int m=(l+r)>>1;
        int ret=0;
        if(L<=m) ret+=query(L,R,lson);
        if(R>m) ret+=query(L,R,rson);
        return ret;
    }
    int main()
    {
        int t,n,ca=1;
        scanf("%d",&t);
        while(t--)
        {
            printf("Case %d:
    ",ca++);
            scanf("%d",&n);
            build(1,n,1);
            char op[10];
            while(scanf("%s",op))
            {
                if(op[0]=='E') break;
                int a,b;
                scanf("%d%d",&a,&b);
                if(op[0]=='Q') printf("%d
    ",query(a,b,1,n,1));
                else if(op[0]=='S') update(a,-b,1,n,1);
                else update(a,b,1,n,1);
            }
        }
        return 0;
    }
  • 相关阅读:
    线程间的通信 与 线程池
    线程同步
    静态代理模式
    多线程状态
    线程、进程、多线程
    Java面向对象之泛型
    ConstraintLayout 用法
    搞NDK开发
    Linux基础命令【记录】
    c# 的一些基本操作或属性
  • 原文地址:https://www.cnblogs.com/54zyq/p/3222818.html
Copyright © 2011-2022 走看看