这里用了树状数组+线段树,也可以完全用线段树来实现
这个是没用懒标记的线段树的版本,当一个区间的元素都加上d时,可以利用差分让线段树维护变成单点修改,从而快速求得变化区间的最大公约数。
#include<iostream>
using namespace std;
const int N = 500010;
typedef long long ll;
struct Node
{
int l, r;
ll v;
}tr[N * 4];
ll b[N], y, x, t[N];
int n, m;
int lowbit(int x)
{
return x & -x;
}
void add(int x, ll c)
{
for (int i = x; i <= n; i += lowbit(i)) t[i] += c;
}
ll sum(int x)
{
ll res = 0;
for (int i = x; i; i -= lowbit(i)) res += t[i];
return res;
}
ll gcd(ll a, ll b)
{
return b ? gcd(b, a % b) : a;
}
void pushup(Node &u, Node &l, Node &r)
{
u.v = gcd(l.v, r.v);
}
void pushup(int u)
{
pushup(tr[u], tr[u << 1], tr[u << 1 | 1]);
}
void build(int u, int l, int r)
{
if (l == r) tr[u] = {l, r, b[l]};
else
{
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
void modify(int u, int x, ll c)
{
if (tr[u].l == x && tr[u].r == x) tr[u].v += c, b[x] += c, add(x, c);
else
{
int mid = tr[u].l + tr[u].r >> 1;
if (x <= mid) modify(u << 1, x, c);
else modify(u << 1 | 1, x, c);
pushup(u);
}
}
ll query(int u, int l, int r)
{
if (l > r) return {0};//注意边界,因为询问的时候是 l + 1 到 r, 当l == r时可能会出界
if (tr[u].l >= l && tr[u].r <= r) return tr[u].v;
else
{
int mid = tr[u].l + tr[u].r >> 1;
if (r <= mid) return query(u << 1, l, r);
else if (l > mid) return query(u << 1 | 1, l, r);
else return gcd(query(u << 1, l, r), query(u << 1 | 1, l, r));
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> x;
b[i] = x - y;
add(i, b[i]), y = x;
}
build(1, 1, n);
char op[2];
ll l, r, d;
while (m --)
{
scanf("%s%lld%lld", op, &l, &r);
if (*op == 'Q')
cout << abs(gcd(sum(l), query(1, l + 1, r))) << endl;//区间最大公约数等于gcd(a[l], gcd(b[l + 1],...b[r]))
else
{
scanf("%lld", &d);
modify(1, l, d);
if (r + 1 <= n) modify(1, r + 1, -d);//注意边界,不然会段错误
}
}
}