Codeforces Round #172 (Div. 2) B. Nearest Fraction

题意:给出x,y ,n ,然后求最近与x/y的a/b,b的值要小于n。如果有相同的分数,输出分母最小的那个,如果分母相同,输出分支最小的那个。

解题过程:如果y<=n,就x/y约分输出,这里要注意约分,就因为忘了约分,WA了一次。。。如果y>n,则从1~n依次求值。因为已知x/y,确定了b的值,a = (x/y)*b,a取整,然后和x/y比较,找最小就行了。

代码:

View Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <math.h>
#include <map>
#include <vector>
#include <stack>
#define  N 1005
#define  INF 100000000
using namespace std ;

double cal( int a , int b )
{
    double t = ( 1.0 * a ) / ( 1.0 * b );
    return t ;
}

int gcd( int a , int b )
{
    if ( b == 0 )
    return a ;
    else
    return gcd( b , a % b ) ;
}

int main()
{
    double x , y ;
    double s , t , a ;
    double ans ;
    int min_a , min_b ,  n , i ;

    while( cin>>x>>y>>n )
    {
        if ( y < n )
        {
            int temp = gcd( x , y ) ;
            //cout<<temp<<endl ;
            printf ( "%d/%d\n" , ( int )x/temp , ( int )y/temp ) ;
        }
        else
        {
            s = x / y ;
            ans = INF ;
            for ( i = 1 ; i <= n ; i++ )
            {
               t = s * i ;
               a = cal( t , i ) ;
               if ( fabs( a - s ) < ans )
               {
                   min_a = ( int ) t ;
                   min_b = i ;
                   ans = fabs( a - s ) ;
               }
               a = cal( t + 1.0 , i ) ;
               if ( fabs ( a - s ) < ans )
               {
                   min_a = ( int )( t + 1.0 );
                   min_b = i ;
                   ans = fabs( a - s ) ;
               }
            }
            int temp = gcd( min_a , min_b ) ;
            printf ( "%d/%d\n" , min_a/temp , min_b/temp ) ;
        }
    }
    return 0 ;
}
原文地址:https://www.cnblogs.com/misty1/p/2954604.html