跳到正文

题解

题解:CF2154C2 No Cost Too Great

WuMin4约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年10月20日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟
题目
CF2154C2

版本

  1. v2当前
  2. v1

思路

对于两个数 a1,a2a_1,a_2,增加它们的代价分别为 b1,b2b_1,b_2,那么在最坏情况下,只需要花费 b1+b2b_1+b_2 的代价就能让 gcd⁡(a1,a2)>1\gcd(a_1,a_2)>1,即 a1,a2a_1,a_2 分别为奇数,全部加 11 就能让它们变成偶数,使得 gcd⁡(a1,a2)≥2\gcd(a_1,a_2)\ge 2。

于是我们将题目中的 nn 个数按照增加代价排序,使得 b1≤b2≤⋯≤bnb_1\le b_2\le\cdots\le b_n,那么最坏情况只需要花费 b1+b2b_1+b_2 的代价即能满足条件。考虑还剩下哪些情况能使得代价不劣于最坏条件。

如果进行的操作次数 ≥2\ge2,除非操作全部对 a1a_1 进行,否则最终的总代价一定会不小于 b1+b2b_1+b_2。于是剩下的情况只剩下了多次操作 a1a_1 或操作不超过 11 次 aia_i。

这时就有人问了,万一出现了多个相等的 b1b_1 怎么办?如果出现了相等的 b1b_1,那么 b2=b1b_2=b_1,最坏情况代价为 2b12b_1,对 a1a_1 操作大于 11 次是一定更劣的,不用考虑。

对于多次操作 a1a_1,可以枚举其他 aja_j 的质因子求出对 a1a_1 的最小操作次数。对于操作不超过 11 次 aia_i,可以求出其他 aja_j 的质因子,枚举 aia_i 和 ai+1a_i+1 的质因子判断是否存在。

代码

C++
#include <bits/stdc++.h>
using namespace std;
struct custom_hash {
	static uint64_t splitmix64(uint64_t x) {
		x += 0x9e3779b97f4a7c15;
		x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
		x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
		return x ^ (x >> 31);
	}
	
	size_t operator()(uint64_t x) const {
		static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
		return splitmix64(x + FIXED_RANDOM);
	}
};
int T,n;
struct node{
	int a,b;
}a[200005];
bool cmp(node x,node y){
	return x.b<y.b;
}
unordered_map<int,int,custom_hash> cnt;
void add(int x,int v){
	for(int i=2;i*i<=x;i++){
		if(x%i==0){
			cnt[i]+=v;
			if(!cnt[i]) cnt.erase(i);
			while(x%i==0) x/=i;
		}
	}
	if(x!=1){
		cnt[x]+=v;
		if(!cnt[x]) cnt.erase(x);
	}
}
bool check(int x){
	for(int i=2;i*i<=x;i++){
		if(x%i==0){
			if(cnt.count(i)) return true;
			while(x%i==0) x/=i;
		}
	}
	if(x!=1)
		if(cnt.count(x)) return true;
	return false;
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	cin>>T;
	while(T--){
		cnt.clear();
		cin>>n;
		for(int i=1;i<=n;i++){
			cin>>a[i].a;
			add(a[i].a,1);
		}
		for(int i=1;i<=n;i++)
			cin>>a[i].b;
		sort(a+1,a+1+n,cmp);
		long long ans=a[1].b+a[2].b;
		add(a[1].a,-1);
		for(pair<int,int> v:cnt)
			ans=min(ans,1ll*(v.first-a[1].a%v.first)%v.first*a[1].b);
		add(a[1].a,1);
		for(int i=2;i<=n;i++){
			add(a[i].a,-1);
			if(check(a[i].a)) ans=min(ans,0ll);
			if(check(a[i].a+1)) ans=min(ans,1ll*a[i].b);
			add(a[i].a,1);
		}
		cout<<ans<<endl;
	}
	return 0; 
}
原文