zoukankan      html  css  js  c++  java
  • 树状数组区间查询和单点更新

    题目链接:https://cn.vjudge.net/contest/66989#problem/A(线段树模板题)

    树状数组可以实现线段树的部分功能,只是写起来比较简单。

    AC代码:

    #include<iostream>
    #include<string>
    #include<cstring>
    #include<iomanip>
    #include<cmath>
    #include<stdio.h>
    #include<vector>
    #include<algorithm>
    using namespace std;
    # define inf 0x3f3f3f3f
    # define maxn 50000+100
    int c[maxn];
    int arr[maxn];
    int n;
    int lowbit(int t)
    {
        return t&(-t);
    }
    void update(int t1, int t2)
    {
        while(t1<=n)
        {
            arr[t1]+=t2;
            t1+=lowbit(t1);
        }
    }
    int sum(int t)
    {
        int ans=0;
        while(t>=1)
        {
            ans+=arr[t];
            t-=lowbit(t);
        }
        return ans;
    }
    int main()
    {
        int T;
        int num=0;
        scanf("%d",&T);
        while(T--)
        {
            memset(c,0,sizeof(c));
            memset(arr,0,sizeof(arr));
            scanf("%d",&n);
            for(int i=1; i<=n; i++)
            {
                scanf("%d",&c[i]);
                update(i,c[i]);
            }
            char str[10];
            printf("Case %d:
    ",++num);
            while(~scanf("%s",str))
            {
                if(str[0]=='E')break;
                if(str[0]=='Q')
                {
                    int t1,t2;
                    scanf("%d%d",&t1,&t2);
                    printf("%d
    ",sum(t2)-sum(t1-1));
                }
                else if(str[0]=='A')
                {
                    int t1,t2;
                    scanf("%d%d",&t1,&t2);
                    update(t1,t2);
                    c[t1]+=t2;
                }
                else if(str[0]=='S')
                {
                    int t1,t2;
                    scanf("%d%d",&t1,&t2);
                    update(t1,-t2);
                    c[t1]-=t2;
                }
            }
        }
        return 0;
    }
    
  • 相关阅读:
    要坚持的好习惯
    Attribute与Property关系
    浅谈ES6中super关键字
    JS权威指南读书笔记(七)
    JS权威指南读书笔记(六)
    JS权威指南读书笔记(五)
    JS权威指南读书笔记(四)
    函数
    对象
    数值
  • 原文地址:https://www.cnblogs.com/letlifestop/p/10262859.html
Copyright © 2011-2022 走看看