洛谷 - 树状数组 (板子代码)
程序员文章站
2022-05-22 10:35:33
...
题目链接
题目:
树状数组的板子代码,该算法是用来频繁的区间修改和区间值查询的算法(log n的时间复杂度)。
AC代码
#include <bits/stdc++.h>
inline int read(){char c = getchar();int x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
const int N = 5e5 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const unsigned long long mod = 998244353;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
int arr[N];
int lowbit(int x)
{
return ((x)&(-1*x));
}//查找最小位的1
void update(int x,int y,int n)
{
for(int i = x;i <= n;i += lowbit(i))
arr[i] += y;
}//区间单点修改
int getsum(int x)
{
int ans = 0;
for(int i = x;i;i -= lowbit(i))
ans += arr[i];
return ans;
}//区间和的查询
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int n,m;
cin >> n >> m;
for(int i = 1,num;i <= n;i++)
{cin >> num;update(i,num,n);}
while(m--)
{
int a,b,c;
cin >> a >> b >> c;
if(a == 1)
update(b,c,n);
else
cout << getsum(c)-getsum(b-1) << endl;
}
}