AcWing # 246 区间最大公约数(线段树维护区间gcd)
solution
我们都知道\(gcd(a, b) = gcd(b, a-b)\)(更相减损术)
我们将上述式子扩展到3项我们就会发现
\(gcd(a,b,c)=gcd(b,b−a,c−b)\)
很明显这就是一个差分数组
我们只需要开一棵线段树来维护差分数组gcd
但是我们发现最前边的这个b我们维护的是当前这个点的差分值
所以这就说明我们还需要开一个东西来维护每一个点的值
而且还要支持区间修改(树状数组是一个好东西)
code
/*
Auther:_Destiny
time:2020.5.6
*/
#include <bits/stdc++.h>
#define ll long long
#define N 2000010
#define M 1010
using namespace std;
int n, m; char ss;
ll a[N], d[N], t[N];
ll read() {
ll s = 0, f = 0; char ch = getchar();
while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
while (isdigit(ch)) s = s * 10 + (ch ^ 48), ch = getchar();
return f ? -s : s;
}
ll gcd(ll a, ll b) {
if (!b) return a;
else return gcd(b, a % b);
}
#define lson rt << 1
#define rson rt << 1 | 1
struct node {
ll gcd;
}tree[N];
void push_up(int rt) {
tree[rt].gcd = abs(gcd(tree[lson].gcd, tree[rson].gcd));
}
void build(int rt, int l, int r) {
if (l == r) {tree[rt].gcd = d[l];return;}
int mid = (l + r) >> 1;
build(lson, l, mid);build(rson, mid + 1, r);
push_up(rt);
}
void update(int rt, ll c, int l, int r, int pow) {
if (l == r) {tree[rt].gcd += c;return;}
int mid = (l + r) >> 1;
if (pow <= mid) update(lson, c, l, mid, pow);
else update(rson, c, mid + 1, r, pow);
push_up(rt);
}
ll query(int rt, int l, int r, int L, int R) {
if (L <= l && r <= R) return tree[rt].gcd;
int mid = (l + r) >> 1;ll g = 0;
if (L <= mid) g = abs(gcd(g, query(lson, l, mid, L, R)));
if (R > mid) g = abs(gcd(g, query(rson, mid + 1, r, L, R)));
return g;
}
int lowbit(int x) {return x & -x;}
void add(int b, ll x) { while (b <= n + 1) t[b] += x, b += lowbit(b); }
ll ask(int b) { ll ans = 0; while (b) ans += t[b], b -= lowbit(b); return ans; }
signed main() {
n = read(), m = read();
for (int i = 1; i <= n; i++) a[i] = read();
for (int i = 1; i <= n + 1; i++) {
d[i] = a[i] - a[i - 1];
add(i, d[i]);
}
build(1, 1, n + 1);
ll x, y, d;
for (int i = 1; i <= m; i++) {
cin >> ss;
if (ss == 'C') {
x = read(), y = read(), d = read();
update(1, d, 1, n + 1, x);
update(1, -d, 1, n + 1, y + 1);
add(x, d), add(y + 1, -d);
} else if (ss == 'Q') {
x = read(), y = read();
ll ans = query(1, 1, n + 1, x + 1, y);
printf("%lld\n", abs(gcd(ans, ask(x))));
}
}
}