题解:P13837 GCD 与 LCM 问题 - 副本
Morgan2025 · · 题解
P13837 GCD 与 LCM 问题 - 副本
题目描述
一共有
每组给定一个正整数
思路分析
可以看到
现在来具体分析一下。
回到原式
移一下项:
考虑最大值
但这似乎对解题没有什么用,所以考虑其性质
由此可得
这时看到还有一个不好处理的
设
将其代入原式中:
移项:
现在可以考虑枚举哪一个了,容易发现如果枚举
于是我们分析
以下是推导过程:
这样便可算出
但是
同理,以下是推导过程:
设
将其代入原式中:
移项:
这样便可算出
这时只有偶数成立,奇数不成立(大家可以自己证明下)。
这时就可以写出一版基础的代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
int read() {
int num = 0, f = 1;
char s = getchar_unlocked();
while (!isdigit(s)) {
if (s == '-') f = -1;
s = getchar_unlocked();
}
while (isdigit(s)) {
num = (num << 1) + (num << 3) + (s ^ 48);
s = getchar_unlocked();
}
return num * f;
}
inline void write(int x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
signed main() {
int t=read();
while(t--){
int a=read();
int c,d,b;
if(a&1){
//注意c从sqrt(a)开始枚举会比较快
for (c=max(sqrt(a),2.0);;c++) {
d=a/(c-1)+2;
b=(c-1)*(d-1)-a;
if(__gcd(b,a%b)==1&&__gcd(c,d)==1)break;
}
}else{
//注意c从sqrt(2*a)开始枚举会比较快,而且这里的c,d必须为偶数
for (c=max((int)(sqrt(2*a)+1)/2*2,4ll);;c+=2) {
d=((a+c)/(c/2-1)+1+1)/2*2;
b=c*d/2-c-d-a+1;
if(__gcd(b,a%b)==1&&__gcd(c/2,d/2)==1)break;
}
}
cout<<b<<" "<<c<<" "<<d<<'\n';
}
return 0;
}
然而这么写我们只能拿到可怜的58分
(其实卡常是可以过的)。
优化
为什么会超时,仔细看可以发现
在这里我选择使用将质因数压成二进制的形式,如
但还有两种特殊情况:
接下来看最终代码:
#include <bits/stdc++.h>
using namespace std;
// #define int long long
#define ll unsigned long long
int read() {
int num = 0, f = 1;
char s = getchar_unlocked();
while (!isdigit(s)) {
if (s == '-') f = -1;
s = getchar_unlocked();
}
while (isdigit(s)) {
num = (num << 1) + (num << 3) + (s ^ 48);
s = getchar_unlocked();
}
return num * f;
}
inline void write(int x) {
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int zhi[50005],ct=0,yu[50005];bool ff[50005];
//zhi:1-233的质数,ct:质数的数量,yu:>233的质数
ll st[50005]={0};
//st:将1-49999的质因数压成二进制
//预处理
void pre(){
//线性筛质数
for(int i=2;i<=223;i++){
if(!ff[i])zhi[++ct]=i;
for(int j=1;j<=ct&&i*zhi[j]<=223;j++){
ff[i*zhi[j]]=1;
if(i%zhi[j]==0)break;
}
}ll oo=2;
//预处理yu和st
for(int i=1;i<50000;i++)yu[i]=i,st[i]=1;
for(int j=1;j<=ct;j++){
//枚举质数会更快,类似于埃氏筛
for(int i=zhi[j];i<50000;i+=zhi[j]){
st[i]|=oo;
while(yu[i]%zhi[j]==0)yu[i]/=zhi[j];
}
oo<<=1;
}
}
//判断互质的函数
bool hz(int x,int y){
//一些特殊情况
if(x==0)return (y==1);
if(x==1||y==1)return 1;
if(x%y==0||y%x==0)return 0;
//如果两者都<=49999就直接判断
if(yu[x]==1&&yu[y]==1)return ((st[x]&st[y])==1);
//否则判断剩下来的质数是否相等
return ((st[x]&st[y])==1)&&(yu[x]!=yu[y]);
}
signed main() {
//别忘了预处理
pre();
int t=read();
while(t--){
int a=read();
int c,d,b;
if(a&1){
//从哪开始枚举真是玄学呢))
for (c=max(sqrt(1.5*a),2.0)+17;;c++) {
d=(a+c)/(c-1)+1;
b=(c-1)*(d-1)-a;
if(hz(a%b,b)&&hz(c,d))break;
}
}else{
//从哪开始枚举真是玄学呢))
for (c=max((int)(sqrt(2*a)+1)/2*2,4);;c+=2) {
d=((a+c)/(c/2-1)+1+1)/2*2;
b=c*d/2-c-d-a+1;
if(hz(a%b,b)&&hz(c/2,d/2))break;
}
}
write(b);putchar(' ');
write(c);putchar(' ');
write(d);putchar('\n');
}
return 0;
}
最后我们以334ms的良好成绩通过。
时间复杂度约为
(时间复杂度比较抽象作者不会算)。