Big Water Problem

简介: Big Water Problem

Big Water Problem


给一个数列,会有多次询问,对于每一次询问,会有两种操作:

1:给定两个整数x, y, 然后在原数组的第x位置上加y;

2:给定两个整数l,r,然后输出数组从第l位加到第r位数字的和并换行


输入描述:

第一行有两个整数n, m(1 <= n, m <= 100000)代表数列的长度和询问的次数

第二行n个数字,对于第i个数字a[i],(0<=a[i]<=100000)。

接下来m行,每一行有三个整数f, x, y。第一个整数f是1或者是2,代表操作类型,如果是1,接下来两个数x,y代表第x的位置上加y,如果是2,则求x到y的和,保证数据合法。

输出描述:

输出每次求和的结果并换行

输入

10 2

1 2 3 4 5 6 7 8 9 10

1 1 9

2 1 10

输出

64

思路:单点修改和求区间和,利用树状数组求解


树状数组的优点是实现简单,效率高省空间。主要用于查询前缀和、区间和及点更新,对点查询、 区间更新效率较低。

#include<bits/stdc++.h>
using namespace std;
int a[101010];
long long m,n;
long long lowbit(int x)
{
    return x&-x;
}
void add(long long i,long long x)
{
    while(i<=n)
    {
        a[i]+=x;
        i+=lowbit(i);
    }
}
long long int sum(long long i)
{
    long long ans=0;
    while(i>0)
    {
        ans+=a[i];
        i-=lowbit(i);
    }
    return ans;
}
int main()
{
    long long int f,x,y;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        add(i,x);
    }
    while(m--)
    {
        cin>>f>>x>>y;
        if(f==1)
        {
            add(x,y);
        }
        else
        {
            cout<<sum(y)-sum(x-1)<<endl;
        }
    }
    return 0;
}

目录
相关文章
|
7月前
|
人工智能
Big Water Problem
Big Water Problem
39 0
Bear and Big Brother
Bear and Big Brother
100 0
Bear and Big Brother
PAT (Advanced Level) Practice - 1096 Consecutive Factors(20 分)
PAT (Advanced Level) Practice - 1096 Consecutive Factors(20 分)
147 0
|
前端开发
HDOJ 1212 Big Number
HDOJ 1212 Big Number
111 0
HDOJ1018Big Number
HDOJ1018Big Number
108 0
The Rising Smart Logistics Industry: How to Use Big Data to Improve Efficiency and Save Costs
This whitepaper will examine Alibaba Cloud’s Cainiao smart logistics cloud and Big Data powered platform and the underlying strategies used to optimiz.
1542 0
The Rising Smart Logistics Industry: How to Use Big Data to Improve Efficiency and Save Costs
lecture 3.2 problem set 3
"Radioactive decay" is the process by which an unstable atom loses energy and emits ionizing particles - what is commonly refered to as radiation.
1140 0
lecture 2.2 problem set 1 and 2
1 COUNTING VOWELS   (10/10 分数) Assume s is a string of lower case characters.
1042 0