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

来源:互联网 发布:java怎么实现文件上传 编辑:程序博客网 时间:2024/04/20 12:38

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 valuex such that it is true or determine that there is no suchx.

Input

Only one line containing two positive integers a andb (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 exceed10 - 9. If there is no suchx 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
原创粉丝点击