dls的数据结构-树状数组
lowbit运算
modify:下表不能有0
题目链接:http://oj.daimayuan.top/course/15/problem/636
一个log的树状数组二分
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5+10;
LL tr[N], a[N];
int n;
int lowbit(int x){
return x & (-x);
}
int modify(int x, LL v){
for(int i = x; i <= n; i += lowbit(i)) tr[i] += v;
}
// 核心代码多理解
LL query(LL s){
int pos = 0;
for(int i = 20; i >= 0; i --){
if(pos + (1 << i) <= n && tr[pos + (1 << i)] <= s){
pos += (1 << i);
// cout << pos << endl;
s -= tr[pos];
}
}
return pos;
}
int main(){
int q; scanf("%d %d", &n, &q);
for(int i = 1; i <= n; i ++) scanf("%lld", &a[i]), modify(i, a[i]);
while(q--){
int op; scanf("%d", &op);
if(op == 1){
int x, d; scanf("%d %d", &x, &d);
modify(x, d - a[x]);
a[x] = d;
}
else if(op == 2){
LL x; scanf("%lld", &x);
printf("%lld\n", query(x));
}
}
return 0;
}
// 高维树状数组
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 510;
LL tr[N][N], a[N][N];
int n, m;
int lowbit(int x){
return x & (-x);
}
int modify(int x, int y, LL v){
for(int i = x; i <= n; i += lowbit(i)){
for(int j = y; j <= m; j += lowbit(j)) tr[i][j] += v;
}
}
LL query(LL x, LL y){
LL sum = 0;
for(int i = x; i ; i -= lowbit(i)){
for(int j = y; j ; j -= lowbit(j)){
sum += tr[i][j];
}
}
return sum;
}
int main(){
int q; scanf("%d %d %d", &n, &m, &q);
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= m; j ++){
int x; scanf("%d", &x);
a[i][j] = x; modify(i, j, x);
}
}
while(q--){
int op; scanf("%d", &op);
if(op == 1){
int x, y, d; scanf("%d %d %d", &x, &y, &d);
modify(x, y, d - a[x][y]);
a[x][y] = d;
}
else if(op == 2){
LL x, y; scanf("%lld %lld", &x, &y);
printf("%lld\n", query(x, y));
}
}
return 0;
}