Solution: 题解 CF1029F Multicolored Markers
令\(c=a+b\)
一个整数边矩形的边长一定是矩形面积的因数
于是这个问题等价于求最大\(i\leqslant\sqrt c,i|c\),使得有\(f\leqslant i,f|a\)且\(\frac{a}{f}\leqslant \frac{c}{i}\),或有\(g\leqslant i,g|b\)且\(\frac{b}{g}\leqslant \frac{c}{i}\),于是输出\(2(i+\frac{c}{i})\)
既然是求最大\(i\),就让\(i\)从\(\lfloor\sqrt c\rfloor\)开始往下枚举
不失一般性,可以假设\(f\leqslant\sqrt a,g\leqslant\sqrt b\)
那么如果矩形\(a\)可以嵌入,就必有\(f\leqslant i\)且\(\frac{a}{f}\leqslant \frac{c}{i}\)
鉴于\(f\)与\(\frac{a}{f}\)在\(f\geqslant 1\)时负相关,可以把\(f\)设为\(i\),然后向下寻找\(a\)的最大因数,判断\(\frac{a}{f}\)是否可行
另外因为外循环中\(i\)是下降的,所以\(f\)在每次循环开始时应设为\(\min(f,i)\)
\(g\)同理
Time complexity: \(O(\sqrt a)\)
Memory complexity: \(O(1)\)
细节见代码(\(1.46\)s / \(12.00\)KB)
//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
#define int long long
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
int x;char c(getchar());bool k;
while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
if(c^'-')k=1,x=c&15;else k=x=0;
while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
return k?x:-x;
}
void wr(int a){
if(a<0)Pc('-'),a=-a;
if(a<=9)Pc(a|'0');
else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(int i(a);i<(b);++i)
#define Frn1(i,a,b) for(int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
int a,b,c,f,g;
signed main(){
c=Rd(a)+Rd(b),f=sqrt(a),g=sqrt(b);
Frn_(i,sqrt(c),1)if(!(c%i)){
f=min(f,i),g=min(g,i);
while(a%f)--f;
if(a/f<=c/i)wr((i+c/i)<<1),exit(0);
while(b%g)--g;
if(b/g<=c/i)wr((i+c/i)<<1),exit(0);
}
exit(0);
}