题目
题目链接:https://www.luogu.com.cn/problem/P3579
对于 \(n\) 组询问,每组询问给定四个整数 \(a,b,c,d\),从区间 \([a,b]\) 和 \([c,d]\) 中任意选取两个整数 \(x\) 和 \(y\),求 \(\gcd(x,y)\) 的最大值是多少。
\(n\leq 1000\),\(1\leq a,b,c,d\leq 10^9\)。
思路
已经完全不会数学了赶快写一道傻逼题假装没忘(不是。
区间 \((l,r]\) 内存在 \(x\) 的倍数当且仅当 \(\lfloor\frac{l}{x}\rfloor<\lfloor\frac{r}{x}\rfloor\)。
直接枚举 \(d\) 复杂度是 \(O(nV)\) 的。发现很多时候 \(\lfloor\frac{a}{x}\rfloor,\lfloor\frac{b}{x}\rfloor,\lfloor\frac{c}{x}\rfloor,\lfloor\frac{d}{x}\rfloor\) 是相同的,整除分块即可。
时间复杂度 \(O(n\sqrt{V})\)。
代码
#include <bits/stdc++.h>
using namespace std;
const int Inf=2e9;
int Q,a,b,c,d,ans;
int main()
{
scanf("%d",&Q);
while (Q--)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
a--; c--; ans=1;
for (int l=1,r;l<=min(b,d);l=r+1)
{
int a1=a/l,b1=b/l,c1=c/l,d1=d/l;
r=min(min(b/b1,d/d1),min((a1?a/a1:Inf),(c1?c/c1:Inf)));
if (a1<b1 && c1<d1) ans=r;
}
printf("%d\n",ans);
}
return 0;
}