【模板】树状数组
现在来填坑,之前落下的知识,现在往回补。之前一直用线段树来顶树状数组和st表,但是跑得慢,写的也慢。。。
单点修改,区间查询:
#include<iostream> #include<cstdio> #include<cmath> #include<ctime> #include<queue> #include<algorithm> #include<cstring> using namespace std; #define duke(i,a,n) for(int i = a;i <= n;i++) #define lv(i,a,n) for(int i = a;i >= n;i--) #define clean(a) memset(a,0,sizeof(a)) const int INF = 1 << 30; const int N = 300005; typedef long long ll; typedef double db; template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < '0' || c > '9') if(c == '-') op = 1; x = c - '0'; while(c = getchar(), c >= '0' && c <= '9') x = x * 10 + c - '0'; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) putchar('-'), x = -x; if(x >= 10) write(x / 10); putchar('0' + x % 10); } int n,m; int tree[2000000]; int lowbit(int x) { return x & -x; } void update(int x,int y) { while(x <= n) tree[x] += y,x += lowbit(x); } int getsum(int x) { int tot = 0; while(x > 0) tot += tree[x],x -= lowbit(x); return tot; } int main() { read(n);read(m); duke(i,1,n) { int a; read(a); update(i,a); } while(m--) { int a,b,c; read(a);read(b);read(c); if(a == 1) update(b,c); else { printf("%d\n",getsum(c) - getsum(b - 1)); } } return 0; }
区间修改,单点查询:(用到了差分思想,注意读入,然后直接查询就是答案)
#include<iostream> #include<cstdio> #include<cmath> #include<ctime> #include<queue> #include<algorithm> #include<cstring> using namespace std; #define duke(i,a,n) for(int i = a;i <= n;i++) #define lv(i,a,n) for(int i = a;i >= n;i--) #define clean(a) memset(a,0,sizeof(a)) const int INF = 1 << 30; const int N = 300005; typedef long long ll; typedef double db; template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < '0' || c > '9') if(c == '-') op = 1; x = c - '0'; while(c = getchar(), c >= '0' && c <= '9') x = x * 10 + c - '0'; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) putchar('-'), x = -x; if(x >= 10) write(x / 10); putchar('0' + x % 10); } int tree[500010],n,m; int lowbit(int x) { return x & -x; } void update(int x,int y) { while(x <= n) { tree[x] += y; x += lowbit(x); } } int query(int x) { int sum = 0; while(x > 0) { sum += tree[x]; x -= lowbit(x); } return sum; } int main() { read(n);read(m); int lst = 0; duke(i,1,n) { int a; read(a); update(i,a - lst); lst = a; } while(m--) { int opt,x,l,r,z; read(opt); if(opt == 1) { read(l);read(r);read(z); update(l,z); update(r + 1,-z); } else { read(x); int tot = 0; tot = query(x); printf("%d\n",tot); } } return 0; }
只想找一个不会伤害我的人