AcWing Problem - 一个简单的整数问题
题目类型:树状数组
题意
有两种操作:
• 求数组中一段区间的和
• 修改数组中某一个数
分析
使用树状数组和差分的思修来维护。时间复杂度 n logn
代码
static int[] C;
static int[] a;
public static void solve() throws IOException {
int n = nextInt();
int m = nextInt();
init(n);
for (int i = 1; i <= n; i++) a[i] = nextInt();
for (int i = 1; i <= n; i++) add(i, a[i] - a[i - 1], n);
while (m-- > 0) {
char op = nextChar();
if (op == 'Q') {
int x = nextInt();
pw.println(query(x));
} else {
int l = nextInt();
int r = nextInt();
int v = nextInt();
add(l, v, n);
add(r + 1, -v, n);
}
}
}
public static void add(int x, int v, int n) {
while (x <= n) {
C[x] += v;
x += lowbit(x);
}
}
public static long query(int x) {
long re = 0;
while (x > 0) {
re += C[x];
x -= lowbit(x);
}
return re;
}
public static int lowbit(int x) { return x &(-x); }
public static void init(int n) {
a = new int[n + 1];
C = new int[n + 1];
}
/*******************************************************************************************/
/********************************************************************************************/
// Fast I/O