备战NOIP——模板复习14
这里只有模板,并不作讲解,仅为路过的各位做一个参考以及用做自己复习的资料,转载注明出处。
树状数组(B.I.T)
单点修改区间查询
/*Copyright: Copyright (c) 2018
*Created on 2018-11-02
*Author: 十甫
*Version 1.0
*Title: BIT-1
*Time: 5 mins
*/
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int size = 10005;
inline int lowbit(int x) {
return x & (-x);
}
int n, arr[size];
inline void add(int a[], int i, int k) {
while(i <= n) {
a[i] += k;
i += lowbit(i);
}
}
inline int query(int a[], int i) {
int res = 0;
while(i) {
res += a[i];
i -= lowbit(i);
}
return res;
}
int main() {
scanf("%d", &n);
for(int i = 1;i <= n;i++) {
int k;
scanf("%d", &k);
add(arr, i, k);
}
int q;
scanf("%d", &q);
while(q--) {
int man;
scanf("%d", &man);
if(man) {
int i, k;
scanf("%d%d", &i, &k);
add(arr, i, k);
} else {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", query(arr, r) - query(arr, l - 1));
}
}
return 0;
}
区间修改单点查询
/*Copyright: Copyright (c) 2018
*Created on 2018-11-02
*Author: 十甫
*Version 1.0
*Title: BIT-2
*Time: 4.5 mins
*/
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int size = 10005;
inline int lowbit(int x) {
return x & (-x);
}
int n, arr[size];
inline void add(int a[], int i, int k) {
while(i <= n) {
a[i] += k;
i += lowbit(i);
}
}
inline int query(int a[], int i) {
int res = 0;
while(i) {
res += a[i];
i -= lowbit(i);
}
return res;
}
int main() {
scanf("%d", &n);
int last = 0;
for(int i = 1;i <= n;i++) {
int k;
scanf("%d", &k);
add(arr, i, k - last);
last = k;
}
int q;
scanf("%d", &q);
while(q--) {
int man;
scanf("%d", &man);
if(man) {
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
add(arr, l, k), add(arr, r + 1, -k);
} else {
int i;
scanf("%d", &i);
printf("%d\n", query(arr, i));
}
}
return 0;
}
区间修改区间查询
/*Copyright: Copyright (c) 2018
*Created on 2018-11-02
*Author: 十甫
*Version 1.0
*Title: BIT-3
*Time: 7 mins
*/
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int size = 10005;
inline int lowbit(int x) {
return x & (-x);
}
int n, num[size], d1[size], d2[size];
inline void add(int a[], int i, int k) {
while(i <= n) {
a[i] += k;
i += lowbit(i);
}
}
inline int query(int a[], int i) {
int res = 0;
while(i) {
res += a[i];
i -= lowbit(i);
}
return res;
}
inline void modify(int l, int r, int k) {
add(d1, l, k), add(d1, r + 1, -k);
add(d2, l, l * k), add(d2, r + 1, -k * (r + 1));
}
inline int enquiry(int l, int r) {
int res = 0;
res += query(num, r) - query(num, l - 1);
res += (r + 1) * query(d1, r) - l * query(d1, l - 1);
res -= query(d2, r) - query(d2, l - 1);
return res;
}
int main() {
scanf("%d", &n);
for(int i = 1;i <= n;i++) {
int k;
scanf("%d", &k);
add(num, i, k);
}
int q;
scanf("%d", &q);
while(q--) {
int man;
scanf("%d", &man);
if(man) {
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
modify(l, r, k);
} else {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", enquiry(l, r));
}
}
return 0;
}
NOIP 2018 RP++