Codeforces Round #320 (Div. 2) C. A Problem about Polyline

C. A Problem about Polyline

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.

Input

Only one line containing two positive integers a and b (1 ≤ a, b ≤ 109).

Output

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.

Sample test(s)
Input
3 1
Output
1.000000000000
Input
1 3
Output
-1
Input
4 1
Output
1.250000000000
Note

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值