zoukankan      html  css  js  c++  java
  • AcWing 242 一个简单整数问题(区间修改 单点查询)

    原题
    该题涉及树状数组又一串操作:

    ① 区间修改
    运用差分的思想,我们新建了一个数组b,初始化为零,对于每个指令"C l r d",我们只需将其转化为以下操作:
    1.把b[l]加上d
    2.再把b[r+1]减去d

    inline void add(int x,int y)
    {
       for(;x<=n;x+=x&-x)
       {
         c[x]+=y;
       }
    }
    
            add(l,j);
            add(r+1,-j);
    

    ② 单点查询
    执行了以上操作后,b数组的前缀和b[1~x]就代表了该指令对a[x]的影响,而在查询指令"Q x"中,我们只需查询前缀和b[1~x],最后再加上a[x]即可

    inline int ask(int x)
    {
       int ans=a[x];
       for(;x;x-=x&-x)
       {
          ans+=c[x];
       }
       return ans;
    }
    

    AC代码:

    #include<bits/stdc++.h>
    using namespace std;
    int n,m,a[100005],c[100005];
    inline int ask(int x)
    {
       int ans=a[x];
       for(;x;x-=x&-x)
       {
          ans+=c[x];
       }
       return ans;
    }
    inline void add(int x,int y)
    {
       for(;x<=n;x+=x&-x)
       {
         c[x]+=y;
       }
    }
    int main()
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++)
          scanf("%d",&a[i]);
        while(m--)
        {
          getchar();
          char ch;
          scanf("%c",&ch);
          if(ch=='Q')
          {
            int x;
            scanf("%d",&x);
            printf("%d
    ",ask(x));
          }
          else
          {
            int l,r,j;
            scanf("%d%d%d",&l,&r,&j);
            add(l,j);
            add(r+1,-j);
          }
        }
    return 0;
    }
    
    

    做了这题,发现自己代码能力好差,找bug找了好久。
    这题用了内联函数,发现也没快多少2333

    戒骄戒躁,百炼成钢!
  • 相关阅读:
    BZOJ3543: [ONTAK2010]Garden
    python初识面向对象
    python装饰器
    python递归函数及二分法查找
    python内置函数及匿名函数
    生成器和生成器函数以及各种推导式
    第一类对象 函数名 变量名
    函数的进阶
    Python初始函数
    Python文件操作
  • 原文地址:https://www.cnblogs.com/Pecoz/p/12397315.html
Copyright © 2011-2022 走看看