思路
对于两个数 ,增加它们的代价分别为 ,那么在最坏情况下,只需要花费 的代价就能让 ,即 分别为奇数,全部加 就能让它们变成偶数,使得 。
于是我们将题目中的 个数按照增加代价排序,使得 ,那么最坏情况只需要花费 的代价即能满足条件。考虑还剩下哪些情况能使得代价不劣于最坏条件。
如果进行的操作次数 ,除非操作全部对 进行,否则最终的总代价一定会不小于 。于是剩下的情况只剩下了多次操作 或操作不超过 次 。
这时就有人问了,万一出现了多个相等的 怎么办?如果出现了相等的 ,那么 ,最坏情况代价为 ,对 操作大于 次是一定更劣的,不用考虑。
对于多次操作 ,可以枚举其他 的质因子求出对 的最小操作次数。对于操作不超过 次 ,可以求出其他 的质因子,枚举 和 的质因子判断是否存在。
代码
#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;
}