题目大意
给定一个长度为N的数列A,以及M条指令(N<= 5e5, M <= 1e5),每条指令可能是一下两种之一:
- “C l r d”,表示A[l], A[l+1], …, A[r]都加上d
- “Q l r”,表示询问A[l], A[l+1], …, A[r]的最大公约数(GCD)
对于每个询问,输出一个整数表示答案
解题思路
两个重要的结论
- gcd(x, y, z) = gcd(x, y - x, z - y)同理可以推广到任意多个数
- gcd(a, b) = gcd(a, -b)
对于原序列a[i],我们可以维护一个差分数组cfgcd, cfgcd[i] = a[i] – a[i-1]
我们对cfgcd建立一个线段树来维护这些数的gcd,我们对区间修改就变成了两次单点修改
而对答案的询问变成了
gcd(a[i], qury(l+1, r))
然后我们用一个差分+树状数组来维护对数组a的区间修改,单点查询
代码
#include <bits/stdc++.h>
#define ll long long
#define qc ios::sync_with_stdio(false); cin.tie(0);cout.tie(0)
#define fi first
#define se second
#define PII pair<int, int>
#define PLL pair<ll, ll>
#define pb push_back
using namespace std;
const int MAXN = 1e6 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll mod = 1e9 + 7;
inline int read()
{
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
ll gcd(ll a, ll b){
a = abs(a);
b = abs(b);
return b ? gcd(b, a%b) : a;
}
// 用于维护区间gcd
int n, m;
ll cfgcd[MAXN]; // 差分数组
ll a[MAXN]; // 原数组
ll tree[MAXN << 2];
// 用于区间修改,单点查询, 差分+树状数组
ll cf[MAXN]; // 差分数组
ll cfsum[MAXN]; // 差分前缀和
int j;
int lowbit(int x){
return x&-x;
}
void add(int x, ll num){
for(int i = x; i <= n; i += lowbit(i)){
cfsum[i] += num;
}
}
ll search(int x){
ll ret = 0;
while(x){
ret += cfsum[x];
x -= lowbit(x);
}
return ret;
}
void pushup(int rt){
tree[rt] = gcd(tree[rt << 1], tree[rt << 1 | 1]);
}
void build(int l, int r, int rt){
if(l == r){
tree[rt] = cfgcd[j++];
return ;
}
int m = (l + r) >> 1;
build(l, m, rt << 1);
build(m+1, r, rt << 1 | 1);
pushup(rt);
}
void update(int L, int R, ll x, int l, int r, int rt){
if(L <= l && r <= R){
tree[rt] += x;
return ;
}
int m = (l + r) >> 1;
if(L <= m)
update(L, R, x, l, m, rt << 1);
if(m < R)
update(L, R, x, m+1, r, rt << 1 | 1);
pushup(rt);
}
ll query(int L, int R, int l, int r, int rt){
if(L <= l && r <= R)
return tree[rt];
int m = (l + r) >> 1;
ll ret = 0;
if(L <= m)
ret = gcd(ret, query(L, R, l, m, rt << 1));
if(m < R)
ret = gcd(ret, query(L, R, m+1, r, rt << 1 | 1));
return ret;
}
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> a[i];
cfgcd[i] = a[i] - a[i-1];
cf[i] = cfgcd[i];
}
j = 1;
for(int i = 1; i <= n; i++)
add(i, cf[i]);
build(1, n, 1);
while(m--){
char c;
cin >> c;
if(c == 'Q'){
int l, r;
cin >> l >> r;
// cout << search(l) << " " << query(l+1, r, 1, n, 1) << endl;
cout << gcd(search(l), query(l+1, r, 1, n, 1)) << endl;
}
else{
int l, r;
ll x;
cin >> l >> r >> x;
add(l, x);
add(r+1, -x);
update(l, l, x, 1, n, 1);
if(r < n)
update(r+1, r+1, -x, 1, n, 1);
}
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
qc;
int T;
// cin >> T;
T = 1;
while(T--){
solve();
}
return 0;
}