跳到正文

题解

P16962 [SCCPC 2026] 交换余生 题解

lucasincyber约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年6月26日
收录
2026年10月4日
更新
2026年11月11日
篇幅
约 5 分钟
获赞
5
题目
P16962

版本

  1. v1当前

题目传送门

思路

首先考虑设 fi=gcd⁡j=1iajf_i = \gcd \limits_{j = 1}^i a_j,gi=gcd⁡j=inajg_i = \gcd \limits_{j = i}^n a_j,即 fif_i 为前缀 gcd⁡\gcd,gig_i 为后缀 gcd⁡\gcd。设 GG 为全局 gcd⁡\gcd,如果 fi=gi+1f_i = g_{i + 1},则 fi,gi+1f_i, g_{i + 1} 一定都等于 GG。

将整个数组除以 GG,则 bb 合法的条件转化为所有 1≤i<n1 \le i < n 都满足 fi≠gi+1f_i \neq g_{i + 1}。我们发现,实际上就是将 bb 分为前、后两个部分,其中前面的部分有最大公因数 p1p_1,后面的部分有最大公因数 p2p_2,且 p1≠p2p_1 \neq p_2。这样我们会发现,bb 合法的条件就是如果存在 p1,p2p_1, p_2 两个不相等的质数,满足既不被 p1p_1 整除也不被 p2p_2 整除的数的个数 ≤1\le 1 就合法。否则就不合法。我们称这个特殊的数为 p3p_3,合法情况就是将 p3p_3 放在前、后两段的分界处上。

为什么呢?将 1≤i<n1 \le i < n 中的 ii 分为三类:

  1. fi=p1f_i = p_1,此时 ii 在前面那个部分,所以 gi+1g_{i + 1} 就等于 p2p_2 或者 11,一定不相等;
  2. gi+1=p2g_{i + 1} = p_2,此时同上,合法;
  3. 如果存在 p3p_3,则无论怎么分段,p3p_3 一定只会影响 fif_i 和 gi+1g_{i + 1} 中的一个,即如果 fif_i 中包含 p3p_3,则 fi=1,gi+1=p2f_i = 1, g_{i + 1} = p_2,反之亦然。

考虑怎么求出 p1,p2p_1, p_2 的存在性。先暴力枚举 p1p_1,我们发现,因为 p3p_3 最多只有一个,所以根据鸽巢原理,a1,a2a_1, a_2 的所有质因子中,一定包含 p1p_1。

接着需要判断存不存在 p2p_2,按照上面的思路,我们将所有 p1∤aip_1 \nmid a_i 的 aia_i 放入集合 SS 中,则 SS 中前两个元素 s1,s2s_1, s_2 的所有质因子中,也一定包含 p2p_2。双重循环暴力枚举即可判断存在性。

时间复杂度 O(TV+(max⁡i≤Vω(i))2⋅∑n)\mathcal{O}(T \sqrt V + (\max \limits_{i \le V} \omega(i))^2 \cdot \sum n),其中 ω(i)\omega(i) 为 ii 的质因数个数。

事实上,只要任意选择 aa 和 SS 中的两个数,就可以得出 p1,p2p_1, p_2,只是为了方便,钦定了前两个数而已。

代码

C++
#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;
}
原文
存档评论2 条抓取于