算法竞赛进阶指南,215页, 线段树,树状数组
本题要点:
1、最大公约数 gcd(x, y) = gcd(x, y - x), 三个数的情况:
gcd(x, y, z) = gcd(x, y - x, z - y), 联想到差分数组, 令 b[i] = a[i] - a[i - 1],
用线段树维护 数组b 的区间最大公约数,
a) 每次 询问 “Q L R” ,就是要求出 gcd(a[L], ask(1, L + 1, R))
注意, L == R 的情况,直接返回 a[L]即可(也就是gcd(a[L], 0))
b) 每次增加操作 “C L R d”, 相当于 b[L] 增加 d, b[R + 1] 减少d(需要做特判,R < n时候,才执行 b[R + 1] 减少d 的操作)
2、数组a 在区间 [L, R] 同时加上d,也就是 “区间增加” 和 "单点查询"的问题。
使用树状数组c 来维护 数组 a的差分数组,c数组起初全为0.
每次在某区间 [L, R] 增加d相当于 c[L] 加上 d, c[R + 1] 减去d,
每次查询a数组的第k的位置值 = a[k] + getSum(k) (a[k] 是数组a的原始值)
3、 注意,使用 long long;
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#define lowbit(i) ((i)&(-i)) // lowbit(x) 表示x的二进制对应的值
using namespace std;
const int MaxN = 500010;
long long a[MaxN], b[MaxN], c[MaxN];//b是数组a的差分序列, c是数组a的树状数组
int n, m;
long long getSum(int x)
{
long long sum = 0;
for(int i = x; i > 0; i-= lowbit(i))
{
sum += c[i];
}
return sum;
}
void update(int x, long long v)
{
for(int i = x; i <= n; i += lowbit(i))
{
c[i] += v;