XTU 1236 Fraction 二分

Fraction

Problem Description:

Everyone has silly periods, especially for RenShengGe. It’s a sunny day, no one knows what happened to RenShengGe, RenShengGe says that he wants to change all decimal fractions between 0 and 1 to fraction. In addtion, he says decimal fractions are too complicate, and set that is much more convient than 0.33333… as an example to support his theory.

So, RenShengGe lists a lot of numbers in textbooks and starts his great work. To his dissapoint, he soon realizes that the denominator of the fraction may be very big which kills the simplicity that support of his theory.

But RenShengGe is famous for his persistence, so he decided to sacrifice some accuracy of fractions. Ok, In his new solution, he confines the denominator in [1,1000] and figure out the least absolute different fractions with the decimal fraction under his restriction. If several fractions satifies the restriction, he chooses the smallest one with simplest formation.

Input

The first line contains a number T(no more than 10000) which represents the number of test cases.

And there followed T lines, each line contains a finite decimal fraction x that satisfies .

Output

For each test case, transform x in RenShengGe’s rule.

Sample Input

3
0.9999999999999
0.3333333333333
0.2222222222222

Sample Output

1/1
1/3
2/9

tip

You can use double to save x;

解题思路:将1000/1000这些数据打表,但是因为要求的是最简,所以用GCD排除最大公约数不为1的数据,接着二分查找对应的数据就好了,但是这个二分和别的二分有些不同,正常的二分,假设x是要找的值,一般都是满足fabs(x1-x)<1e-6就可以了,但这道题不能这样做,因为要找的值是近似的,可能有些要小于2e-13,另一些些又要小于1e-12,所以不能那样,我们要不断二分找到最近似的那个值。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

struct table
{
    int i;
    int j;
    double x;
    friend bool operator<(const table a1,const table b1)
    {
        return a1.x<b1.x;
    }
} w[600000];
int main()
{
    int a=0;
    for(int i=1; i<=1000; i++)
        for(int j=0; j<=i; j++)
        {
            if(__gcd(i,j)==1)
            {
                w[a].i=i;
                w[a].j=j;
                w[a++].x=1.0*j/i;
            }
        }
    sort(w,w+a);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        double x;
        scanf("%lf",&x);
        int l=0,r=a-1,mid;
        while(r-l!=1)
        {
            mid=(l+r)>>1;
            if(w[mid].x>=x)  r=mid;
            else l=mid;
        }
        if(fabs(w[l].x-x)<fabs(w[r].x-x))
          printf("%d/%d\n",w[l].j,w[l].i);
     else   printf("%d/%d\n",w[r].j,w[r].i);
    }
    return 0;
}

你可能感兴趣的:(二分查找,ACM)