Codeforces #172 div2的B题

B. Nearest Fraction
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction  whose denominator is no more than n.

Formally, you should find such pair of integers a, b (1 ≤ b ≤ n; 0 ≤ a) that the value  is as minimal as possible.

If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.

Input

A single line contains three integers x, y, n (1 ≤ x, y, n ≤ 105).

Output

Print the required fraction in the format "a/b" (without quotes).

Sample test(s)
input
3 7 6
output
2/5
input
7 2 4
output
7/2

题目意思还是很清楚的,要找一个分数使得它与x/y的差最小,要求分母b<n,b要最小,分子也最小的那个。

昨晚纠结了半天,还是没纠结出来,今天把它a了。。。。。。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
double go(double xy,int a,int b)
{
    double s=((double)a)/((double)b)-xy;
    if(s>0)return s;
    else return -s;
}
int main()
{
    int x,y,n;
    while(scanf("%d%d%d",&x,&y,&n)!=EOF)
    {
        double xy=((double)x)/((double)y);
        int a,b,j=0;
        double ss=110005,v;
        for(int i=1;i<=n;i++)
        {
            while(go(xy,j,i)>go(xy,j+1,i))j++;
            v=go(xy,j,i);
            if(v<ss)
            {
                ss=v;
                a=j;
                b=i;
            }
            if(ss==0)break;
        }
        cout<<a<<"/"<<b<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值