跳到正文

个人记录

题解:QOJ 17978 It's a Mod, Mod, Mod, Mod World 2

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

文章信息

发布
2026年11月16日
收录
2026年11月16日
更新
2026年11月16日
篇幅
约 5 分钟

版本

  1. v1当前

吓哭了是人类智慧题。

QOJ 17978 It’s a Mod, Mod, Mod, Mod World 2

给出 S={a1,a2,⋯ ,an}S=\{a_1,a_2,\cdots,a_n\}。求最大子集 T⊆ST\subseteq S 使得存在 k≥2k\ge 2,TT 的所有元素在模 kk 意义下同余。

Solution

首先你发现只有 kk 是质数才是有用的。

证明

考虑 kk 不是质数,则存在质数 pp 使得 p∣kp\mid k。设你选的集合为 T={b1,b2,⋯ ,bm}T=\{b_1,b_2,\cdots,b_m\}。因为 bi≡r(modk)b_i\equiv r\pmod k,所以 bi≡r(modp)b_i\equiv r\pmod p。同余集不会变小。故选择 pp 不劣。

但你发现质数还是很多。先考虑答案的下界。你发现答案至少是 ⌈n2⌉\lceil\frac{n}{2}\rceil。

证明

考虑 k=2k=2 然后抽屉原理。

这说明作为答案的 ∣Tmax⁡∣|T_{\max}| 至少是 ⌈n2⌉\lceil\frac{n}{2}\rceil。这告诉我们什么?你随机选一个数 x∈Sx\in S,它在 Tmax⁡T_{\max} 内的概率至少是 12\frac{1}{2}。

你发现一个数不足以确定。考虑再随机一个数 y∈Sy\in S。那两个数都在 Tmax⁡T_{\max} 内的概率大概是 14\frac{1}{4}。

这个概率好像不是很小。不妨假设 x,yx,y 都在 Tmax⁡T_{\max} 内。发扬人类智慧。你注意到 k∣∣x−y∣k\mid |x-y| 等价于 x≡y(modk)x\equiv y\pmod k。又因为 kk 是指数,所以最优的 kk 一定是 ∣x−y∣|x-y| 的某个质因子。考虑随机 T=30T=30 次,这样取不到两个在 Tmax⁡T_{\max} 内的数的概率实际非常小。你发现这样是有正确性的。

证明

假设某一次没取到,那答案不会更优。所以这样是对的。

那不是直接把 ∣x−y∣|x-y| 所有质因子求出来然后试一遍就行了。你发现去重后,候选质因子集合大小实际上很小。

证明

注意到一个数的质因子种类数 ω(n)\omega(n) 的期望是 O(log⁡log⁡n)\mathcal O(\log\log n)。你随机 TT 个这样的数,上界为 O(Tlog⁡log⁡n)\mathcal O(T\log\log n)(而且取不到)。

使用 Pollard-rho 算法,期望时间复杂度 O ⁣(n+T(V14+nlog⁡log⁡V))\mathcal O\!\left(n+T\left(V^{\frac{1}{4}}+n\log\log V\right)\right)。我不会 Pollard-rho 怎么办!考虑把 [1,V][1,\sqrt V] 的质数筛出来然后用这些质数做质因数分解,时间复杂度 O ⁣(n+Vlog⁡log⁡V+T(Vlog⁡V+nlog⁡log⁡V))\mathcal O\!\left(n+\sqrt{V}\log\log V+T\left(\dfrac{\sqrt{V}}{\log V}+n\log\log V\right)\right)。

代码
C++
constexpr int N=20005;
constexpr int L=40000;
int n;
int a[N];
int pr[L+5],m=0;
bitset<L+5>npr;
mt19937 RNG(time(0));
unordered_set<int>cand;
unordered_map<int,int>cnt;
void sieve(){
	npr[0]=npr[1]=true;
	for(int i=2;i<=L;i++){
		if(!npr[i]){
			pr[++m]=i;
			for(int j=i<<1;j<=L;j+=i){
				npr[j]=true;
			}
		}
	}
}
void factor(int n){
	for(int i=1;i<=m&&pr[i]*pr[i]<=n;i++){
		if(n%pr[i]==0)cand.insert(pr[i]);
		while(n%pr[i]==0)n/=pr[i];
	}
	if(n!=1)cand.insert(n);
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	sieve();
	read(n);
	int ans=0;
	for(int i=1;i<=n;i++){
		read(a[i]);
		if(a[i]&1)ans++;
	}
	ans=max(ans,n-ans);
	for(int _=1;_<=30;_++){
		const int x=a[RNG()%n+1];
		const int y=a[RNG()%n+1];
		const int diff=abs(x-y);
		if(diff)factor(diff);
	}
	for(const int &p:cand){
		cnt.clear();
		for(int i=1;i<=n;i++){
			cnt[a[i]%p]++;
			ans=max(ans,cnt[a[i]%p]);
		}
	}
	write(ans);
	return 0;
}
原文