There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – ....
We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.
Only one line containing two positive integers a and b (1 ≤ a, b ≤ 109).
Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output - 1 as the answer.
3 1
1.000000000000
1 3
-1
4 1
1.250000000000
You can see following graphs for sample 1 and sample 3.
理解题意后就发现其实含义很简单。
如图所示,每次坐标点对折线有三种情况:
1.位于上坡
2.位于下坡
3.不可能在折线上
假设坐标点之前经历了n个周期:
1.a=2nx+b=> x=(a-b)/2n;
2.a=(2n+1)x+(x-b)=2(n+1)x-b=> x=(a+b)/(2n+2)
由题意可知,a,b>0,则两种情况x>=b,即a>=(2n+1)b;
先处理a<=b时的情况。a<b时,输出-1即可;a=b时,输出a即可。
此时只剩a>b情况,找到第一个n令a<(2n+1)b;取k=n-1,找到a=2kx+b与a=(2k+1)x+(x-b)=2(k+1)x-b两者最小值输出即可。若找不到则输出-1。
还有需要注意的是,虽然a,b在int范围内,但判断a与(2n+1)b大小时,会爆int,耿直的wa了,加括号long long即可。
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <stack>
#include <cmath>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define N 100005
#define INF 0x3f3f3f3f;
int main() {
int a,b;
double x,t1,t2;
cin>>a>>b;
if (a==b) {
cout<<a<<endl;
return 0;
}
if (b>a) {
cout<<"-1"<<endl;
return 0;
}
double minx=(double)(1<<30);
for (int i=1; ; i++) {
if (a<(long long)(2*i+1)*b) {
i--;
if(i>0) t1=(a-b)*1.0/(2.0*i);
else t1=(double)(1<<30);
t2=(a+b)*1.0/(2.0*(i+1));
minx=min(t1,t2);
break;
}
}
if(minx==(double)(1<<30)) cout<<"-1"<<endl;
else
printf("%.9lf\n",minx);
return 0;
}