[BZOJ1684]&&[Usaco2005 Oct]Close Encounter

描述 Description

Lacking even a fifth grade education, the cows are having trouble with a fraction problem from their textbook. Please help them. The problem is simple: Given a properly reduced fraction (i.e., the greatest common divisor of the numerator and denominator is 1, so the fraction cannot be further reduced) find the smallest properly reduced fraction with numerator and denominator in the range 1..32,767 that is closest (but not equal) to the given fraction. 找一个分数它最接近给出一个分数. 你要找的分数的值的范围在 1..32767

输入格式 InputFormat

Line 1: Two positive space-separated integers N and D (1 <= N < D <= 32,767), respectively the numerator and denominator of the given fraction

输出格式 OutputFormat

Line 1: Two space-separated integers, respectively the numerator and denominator of the smallest, closest fraction different from the input fraction.

样例输入 SampleInput

6133 23254

样例输出 SampleOutput

3508 13301

来源 Source

Silver


BZOJ 1684


代码 Code

a/b=n/d 得 ad=bn,于是枚举 b=1 -> 32767,a=round(b*n/d)。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int inf=0x7fffffff/11.27;
const int maxn=32767;
int a,b,i,j,t,n,m,l,r,k,z,y,x,d;
long double f,ans;
inline void read(int &x)
{
    x=0;char ch=getchar();
    while (ch<'0' || ch>'9') ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
}
inline void update(int a,int b)
{
    if (fabs((double)a/b-f)<ans)
    {
        ans=fabs((double)a/b-f);
        x=a;y=b;
    }
}
int main()
{
    read(n);read(d);
    f=(double)n/d;ans=inf;
    for (b=1;b<=maxn;b++)
    {
        a=round((double)b*n/d);
        if (a*d==b*n)
        {
            update(a+1,b);
            update(a-1,b);
        }
        else update(a,b);
    }
    printf("%d %d\n",x,y);
    return 0;
}