GCD 与 LCM 问题 - 副本

· · 题解

前言

弱化题解,中等题解,加强题解。

题目分析

继续中等的思路,我们拆成 a+b-\gcd(a,b)=\operatorname{lcm}(c,d)-c-d。

式子两边没有任何关系,那就分开想。

首先你尝试把右边式子的值尽量都求出来,但是时间复杂度显然不允许。你需要挑选一部分,你希望用尽量小的数凑出来尽量大的乘积,因此两者最大公约数应该不超过 2。显然用两个质数和两个质数的二倍即可。

右边式子也是类似的,你先枚举质数,再枚举不是质数的数。这样的话时间也不太会爆炸。正确性可以打表验证。

唯一的时间瓶颈是对每一对 (c,d) 和值映射,用哈希表存的话会有大约 2.5\times 10^7 次。但是如果离线之后只对 T 组询问存的话就只需要 3\times 10^5。

代码

#include<bits/stdc++.h>
#include<bits/extc++.h>
#define int long long
using namespace std;
using __gnu_pbds::gp_hash_table;
constexpr int N=5e4,Inf=1e9;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
struct Hsh{
    size_t operator()(int x)const{
        static int s1=rng(),s2=rng(),s3=rng();
        x+=s1,
        x=(x^(x>>33))+s2,
        x=(x^(x>>30))+s3;
        return x;
    }
};
int T;
vector<int>pr,perm;
bitset<N>isp;
bitset<Inf+N>isexistcd,queries;
gp_hash_table<int,array<int,2>,Hsh>answer;
vector<array<int,2> >ans;
void getpr(){
    isp.set();
    isp[0]=isp[1]=0;
    for(int i=2;i<N;i++){
        if(isp[i])
            pr.push_back(i);
        for(auto j:pr){
            if(i*j<N)
                isp[i*j]=0;
            if(i%j==0)
                break;
        }
    }
    return;
}
void init(){
    vector<int>tmp;
    for(int i=1;i<N;i++)
        if(isp[i])
            perm.push_back(i);
        else
            tmp.push_back(i);
    shuffle(tmp.begin(),tmp.end(),rng);
    for(auto p:tmp)
        perm.push_back(p);
    for(auto p:pr)
        for(auto q:pr){
            if(p==q||p*q<=p+q||p*q-(p+q)>=Inf+N)
                continue;
            isexistcd[p*q-(p+q)]=1;
            if(2*p>=N||2*q>=N||2*(p*q-(p+q))>=Inf+N)
                continue;
            isexistcd[2*(p*q-(p+q))]=1;
        }
    return;
}
void calc(){
    for(auto p:pr)
        for(auto q:pr){
            if(p==q||p*q<=p+q||p*q-(p+q)>=Inf+N)
                continue;
            if(queries[p*q-(p+q)])
                answer[p*q-(p+q)]={p,q},queries[p*q-(p+q)]=0;
            if(2*p>=N||2*q>=N||2*(p*q-(p+q))>=Inf+N)
                continue;
            if(queries[2*(p*q-(p+q))])
                answer[2*(p*q-(p+q))]={2*p,2*q},queries[2*(p*q-(p+q))]=0;
        }
    return;
}
string program(){
    cin.tie(nullptr)->ios::sync_with_stdio(0);
    getpr(),init();
    for(cin>>T;T;T--){
        int a;
        cin>>a;
        for(auto b:perm){
            int x;
            if(isp[b]){
                if(a%b==0)
                    x=a;
                else
                    x=a+b-1;
            }
            else
                x=a+b-gcd(a,b);
            if(isexistcd[x]){
                ans.push_back({b,x}),queries[x]=1;
                break;
            }
        }
    }
    calc();
    for(auto&[b,x]:ans){
        auto[c,d]=answer[x];
        println("{} {} {}",b,c,d);
    }
    return"H17";
}
string H17=program();
signed main(){
    return 0;
}