B. Playing with GCD
B. Playing with GCD
You are given an integer array of length .
Does there exist an array consisting of positive integers such that for all (?
Note that denotes the greatest common divisor (GCD) of integers and .
Input
Each test contains multiple test cases. The first line contains the number of test cases (). Description of the test cases follows.
The first line of each test case contains an integer () — the length of the array .
The second line of each test case contains space-separated integers representing the array ().
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output "" if such exists, otherwise output "". 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 .
In the second test case, one possibility for is .
In the third test case, it can be proved that there does not exist any array b that fulfills all the conditions.
解题思路
比赛的时候想了快一个小时都没想到怎么做。关键就是在于根据已有的数组去构造出数组。
对于,有,,可以发现既是的倍数,也是的倍数,即满足,因此就是和的公倍数。但这里我们取,这是因为如果取最小公倍数的倍数的话,即,是大于的整数,那么就有
即对于任意的如果不是取,那么经过求gcd操作后得到的不一定是原来的数组(跟确切的意思是,如果每一个都满足,且经过gcd操作后可以得到数组,那么如果的构造方式为,此时经过gcd操作后就不一定可以得到数组,因为得到的结果可能是原来位置上的数的倍数)。
当然,如果,那么;如果,那么。
最后还要判断构造得到的数组经过gcd操作后能否得到数组,如果发现,那么就不存在解。
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效