跳到正文

个人记录

树状数组

Khotcrsty约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年7月28日
更新
2026年7月28日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
#define iosFast ios :: sync_with_stdio ( false ); cin.tie ( nullptr ); cout.tie( nullptr )
#define rep(i, a, b) for ( int i = (a); i <= (b); i ++ )
#define per(i, a, b) for ( int i = (a); i >= (b); i -- )
#define debug(x) cerr << #x << " is " << ( x ) << endl
#define lcm(a, b) ( ( a ) / __gcd( a, b ) * ( b ) )
#define popcount(x) __builtin_popcountll( x )
#define println(x) cout << ( x ) << endl
#define printSpace(x) cout << x << " "
#define iseven(x) ( ( ( x ) & 1 ) == 0 )
#define isodd(x) ( ( ( x ) & 1 ) == 1 )
#define lowbit(x) ( ( x ) & ( - x ) )
#define gcd(x, y) __gcd ( x, y )
#define push_back emplace_back
#define PII pair< int, int >
#define Rint register int
#define int long long
#define Sint size_t
#define endl "\n"
using namespace std;
const int N = 1e6 + 10;
int n;int a [ N ];
class BinaryITree {
	public:
		int Tree [ N ];
		inline void Add ( int x, int y ) {
			while ( x <= n ) {
				Tree [ x ] += y;
				x += lowbit ( x );
			}
		}
		inline int query ( int l, int r ) { return ask ( r ) - ask ( l - 1 ); }
	private:
		inline int ask ( int pos ) {
			int ans = 0;
			while ( pos ) {
				ans += Tree [ pos ];
				pos -= lowbit ( pos ); 
			}
			return ans; 
		}
	
};
signed main ( )
{
  iosFast;
  int T;
  cin >> n >> T;
  BinaryITree tree;
  for ( int i = 1; i <= n; i ++ ) cin >> a [ i ], tree.Add ( i, a[ i ] );
  while ( T -- ) {
  	int op, x, y;
  	cin >> op >> x >> y;
  	if ( op == 1 ) a [ x ] += y, tree.Add ( x, y );
  	else cout << tree.query( x, y ) << endl;
  }
  return 0;
}
原文