P16962 [SCCPC 2026] 交换余生 题解
lucasincyber · · 题解
题目传送门
思路
首先考虑设
将整个数组除以
为什么呢?将
-
-
- 如果存在
p_3 ,则无论怎么分段,p_3 一定只会影响f_i 和g_{i + 1} 中的一个,即如果f_i 中包含p_3 ,则f_i = 1, g_{i + 1} = p_2 ,反之亦然。
考虑怎么求出
接着需要判断存不存在
时间复杂度
事实上,只要任意选择
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 5;
int t, n;
int a[N];
vector<int> factorize(int x)
{
vector<int> res;
for (int i = 2; i <= x / i; i++)
{
if (x % i == 0)
{
res.push_back(i);
while (x % i == 0) x /= i;
}
}
if (x > 1) res.push_back(x);
return res;
}
vector<int> merge(vector<int> a, vector<int> b)
{
vector<int> res;
for (int i : a) res.push_back(i);
for (int i : b) res.push_back(i);
sort(res.begin(), res.end());
res.erase(unique(res.begin(), res.end()), res.end());
return res;
}
void solve()
{
scanf("%lld", &n);
for (int i = 1; i <= n; i++)
scanf("%lld", &a[i]);
int tmp = a[1];
for (int i = 2; i <= n; i++)
tmp = __gcd(tmp, a[i]);
for (int i = 1; i <= n; i++)
a[i] /= tmp;
vector<int> pr1 = factorize(a[1]), pr2 = factorize(a[2]);
vector<int> now = merge(pr1, pr2);
for (int p1 : now)
{
vector<int> s;
for (int i = 1; i <= n; i++)
if (a[i] % p1 != 0) s.push_back(a[i]);
if (s.size() <= 1)
{
printf("YES\n");
return;
}
vector<int> pr3 = factorize(s[0]), pr4 = factorize(s[1]);
vector<int> now2 = merge(pr3, pr4);
for (int p2 : now2)
{
int cnt = 0;
for (int i : s) cnt += (i % p2 != 0);
if (cnt <= 1)
{
printf("YES\n");
return;
}
}
}
printf("NO\n");
}
signed main()
{
scanf("%lld", &t);
while (t--) solve();
return 0;
}