Codeforces #506 F. Multicolored Markers

F. Multicolored Markers

time limit per test: 3 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

There is an infinite board of square tiles. Initially all tiles are white.

Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be exactly a red tiles and exactly b blue tiles across the board.

Vova wants to color such a set of tiles that:

  • they would form a rectangle, consisting of exactly a+b colored tiles;
  • all tiles of at least one color would also form a rectangle.

Among all correct colorings Vova wants to choose the one with the minimal perimeter. What is the minimal perimeter Vova can obtain?

It is guaranteed that there exists at least one correct coloring.

Input

A single line contains two integers a and b (1≤a,b≤10^14) — the number of tiles red marker should color and the number of tiles blue marker should color, respectively.

Output

Print a single integer — the minimal perimeter of a colored rectangle Vova can obtain by coloring exactly a tiles red and exactly b tiles blue.

It is guaranteed that there exists at least one correct coloring.

Examples

input

3 9

output

14

input

9 3

output

14

input

506 2708

output

3218

概述

   用a个红块和b个蓝块组成大矩形,同时要求其中一个颜色的所有块也排列成矩形,问大矩形的最大周长。

思路

    要求时间复杂度O(sqrt(n))。

  •     c个块组成了宽w高h的矩形,可以写作数学式c=w*h
  •     设c=a+b个块组成了宽wc高hc的矩形,a个块能够组成宽wa高ha的矩形。不妨设wi>=hi,则wa*ha矩形能放入wc*hc矩形的充要条件是wa<=wc 且 ha<=hc

    以上就是搜索的框架。

    由于w与h呈反比关系,搜索wc的同时将wa和wb搜索到<=wc,可以做到线性更新min(ha,hb),以判断符合(wa<=wc && ha<=hc)的wa,ha是否存在。

    在w<h的前提下搜索w最大次数是sqrt(n),总时间复杂度O(sqrt(a+b)),满足时间要求。

代码

#include<bits\stdc++.h> 
typedef long long ll;
using namespace std; 

int main(){
	ll a,b,c;
	cin>>a>>b;
	c=a+b;
	int sqrta=sqrt(a);
	int sqrtb=sqrt(b);
	int sqrtc=sqrt(c);
	ll m=c,r=0;
	for(int cl=1;cl<=sqrtc;cl++){
		if(cl<=sqrta && a%cl==0) m=min(m,a/cl);
		if(cl<=sqrtb && b%cl==0) m=min(m,b/cl);
		if(c%cl==0){
			ll cr=c/cl;
			if(cr>=m) r=(cl+cr)*2;
		}
	} 
	cout<<r;
	return 0;
}

http://www.cnblogs.com/hizcard/  转载请注明出处 

猜你喜欢

转载自blog.csdn.net/hizcard/article/details/82152506
今日推荐