B. Playing with GCD
B. Playing with GCD
You are given an integer array $a$ of length $n$.
Does there exist an array $b$ consisting of $n+1$ positive integers such that $a_i=gcd(b_i,b_{i+1})$ for all $i$ ($1 \leq i \leq n)$?
Note that $gcd(x,y)$ denotes the greatest common divisor (GCD) of integers $x$ and $y$.
Input
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq {10}^{5}$). Description of the test cases follows.
The first line of each test case contains an integer $n$ ($1 \leq n \leq {10}^{5}$) — the length of the array $a$.
The second line of each test case contains $n$ space-separated integers $a_1,a_2, \dots ,a_n$ representing the array $a$ ($1 \leq a_i \leq {10}^{4}$).
It is guaranteed that the sum of $n$ over all test cases does not exceed ${10}^{5}$.
Output
For each test case, output "$\text{YES}$" if such $b$ exists, otherwise output "$\text{NO}$". You can print each letter in any case (upper or lower).
Example
input
4 1 343 2 4 2 3 4 2 4 4 1 1 1 1
output
YES
YES
NO
YES
Note
In the first test case, we can take $b=[343,343]$.
In the second test case, one possibility for $b$ is $b=[12,8,6]$.
In the third test case, it can be proved that there does not exist any array b that fulfills all the conditions.
解题思路
比赛的时候想了快一个小时都没想到怎么做。关键就是在于根据已有的数组$a$去构造出数组$b$。
对于$a_i$,有$a_{i-1} = gcd(b_{i-1}, b_{i})$,$a_{i} = gcd(b_{i}, b_{i+1})$,可以发现$b_i$既是$a_{i-1}$的倍数,也是$a_i$的倍数,即满足$b_i \, \% \, a_{i-1} = 0, \, b_i \, \% \, a_i = 0$,因此$b_i$就是$a_{i-1}$和$a_{i}$的公倍数。但这里我们取$b_i = lcm(a_{i-1},a_{i})$,这是因为如果$b_i$取最小公倍数的倍数的话,即$k \times lcm(a_{i-1}, a_{i})$,$k$是大于$1$的整数,那么就有$$gcd(b_{i}, b_{i+1}) = gcd(k_{i} \times lcm(a_{i-1},a_{i}), k_{i+1} \times lcm(a_{i},a_{i+1})) ~\geq~ gcd(lcm(a_{i-1},a_{i}), lcm(a_{i},a_{i+1})) = a_{i}$$
即对于任意的$b_i$如果不是取$lcm(a_{i-1},a_{i})$,那么经过求gcd操作后得到的不一定是原来的$a$数组(跟确切的意思是,如果每一个$b_i$都满足$b_i = lcm(a_{i-1},a_{i})$,且经过gcd操作后可以得到$a$数组,那么如果$b$的构造方式为$b_i = k_i \times lcm(a_{i-1}, a_{i})$,此时经过gcd操作后就不一定可以得到$a$数组,因为得到的结果可能是原来位置上的数的倍数)。
当然,如果$i = 1$,那么$b_1 = a_1$;如果$i = n$,那么$b_{n+1} = a_n$。
最后还要判断构造得到的$b$数组经过gcd操作后能否得到$a$数组,如果发现$gcd(b_{i}, b_{i+1}) \ne a_{i}$,那么就不存在解。
AC代码如下:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int N = 1e5 + 10; 5 6 int a[N], b[N]; 7 8 int gcd(int a, int b) { 9 return b ? gcd(b, a % b) : a; 10 } 11 12 void solve() { 13 int n; 14 scanf("%d", &n); 15 for (int i = 0; i < n; i++) { 16 scanf("%d", a + i); 17 } 18 b[0] = a[0], b[n] = a[n - 1]; 19 for (int i = 1; i < n; i++) { 20 b[i] = a[i] / gcd(a[i], a[i - 1]) * a[i - 1]; // lcm(a[i], a[i - 1]) 21 } 22 for (int i = 0; i < n; i++) { 23 if (gcd(b[i], b[i + 1]) != a[i]) { 24 printf("NO\n"); 25 return; 26 } 27 } 28 printf("YES\n"); 29 } 30 31 int main() { 32 int t; 33 scanf("%d", &t); 34 while (t--) { 35 solve(); 36 } 37 38 return 0; 39 }
参考资料
Codeforces Round #825 (Div. 2) Editorial:https://codeforces.com/contest/1736
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/16779381.html