Bash likes playing with arrays. He has an array a1, a2, ... an of n integers. He likes to guess the greatest common divisor (gcd) of different segments of the array. Of course, sometimes the guess is not correct. However, Bash will be satisfied if his guess is almost correct.
Suppose he guesses that the gcd of the elements in the range [l, r] of a is x. He considers the guess to be almost correct if he can change at most one element in the segment such that the gcd of the segment is x after making the change. Note that when he guesses, he doesn't actually change the array — he just wonders if the gcd of the segment can be made x. Apart from this, he also sometimes makes changes to the array itself.
Since he can't figure it out himself, Bash wants you to tell him which of his guesses are almost correct. Formally, you have to process qqueries of one of the following forms:
Note: The array is 1-indexed.
The first line contains an integer n (1 ≤ n ≤ 5·105) — the size of the array.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.
The third line contains an integer q (1 ≤ q ≤ 4·105) — the number of queries.
The next q lines describe the queries and may have one of the following forms:
Guaranteed, that there is at least one query of first type.
For each query of first type, output "YES" (without quotes) if Bash's guess is almost correct and "NO" (without quotes) otherwise.
3 2 6 3 4 1 1 2 2 1 1 3 3 2 1 9 1 1 3 2
YES YES NO
5 1 2 3 4 5 6 1 1 4 2 2 3 6 1 1 4 2 1 1 5 2 2 5 10 1 1 5 2
NO YES NO YES
题意:
对于长度为n的数列有两种操作:
①询问L, R, x:区间[L, R]是否能将最多一个数字修改成x后它们Gcd为x,YESorNO
②修改x,y:将第x个数改成y
用线段树维护一个区间的Gcd,修改直接就是单点修改
不过询问允许你将区间中一个数字改成x
也就是说区间[L, R]是否满足最多只有一个数不是x的倍数
线段树区间查询的时候直接查询Gcd不是x倍数的区间即可!如果这样的区间超过1个就一定是NO!
显然真正递归到叶子的区间只会有1个,所以复杂度O(nlogn)
#include
int tre[2222222];
int Gcd(int a, int b)
{
if(b==0)
return a;
return Gcd(b, a%b);
}
void Create(int l, int r, int x)
{
int m;
if(l==r)
{
scanf("%d", &tre[x]);
return;
}
m = (l+r)/2;
Create(l, m, x*2);
Create(m+1, r, x*2+1);
tre[x] = Gcd(tre[x*2], tre[x*2+1]);
}
void Update(int l, int r, int x, int a, int b)
{
int m;
if(l==r)
{
tre[x] = b;
return;
}
m = (l+r)/2;
if(a<=m)
Update(l, m, x*2, a, b);
else
Update(m+1, r, x*2+1, a, b);
tre[x] = Gcd(tre[x*2], tre[x*2+1]);
}
int Query(int l, int r, int x, int a, int b, int mt)
{
int m, ans = 0;
if(l==r)
return 1;
m = (l+r)/2;
if(a<=m && tre[x*2]%mt!=0)
ans = Query(l, m, x*2, a, b, mt);
if(b>=m+1 && tre[x*2+1]%mt!=0 && ans<=1)
ans += Query(m+1, r, x*2+1, a, b, mt);
return ans;
}
int main(void)
{
int n, q, opt, L, R, x, y;
scanf("%d", &n);
Create(1, n, 1);
scanf("%d", &q);
while(q--)
{
scanf("%d", &opt);
if(opt==1)
{
scanf("%d%d%d", &L, &R, &x);
if(Query(1, n, 1, L, R, x)<=1)
printf("YES\n");
else
printf("NO\n");
}
else
{
scanf("%d%d", &x, &y);
Update(1, n, 1, x, y);
}
}
return 0;
}