题解:CF2154C2 No Cost Too Great

· · 题解

思路

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

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

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

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

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

代码

#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; 
}