E - RealPhobia HDU - 4180

Bert is a programmer with a real fear of floating point arithmetic. Bert has quite successfully used rational numbers to write his programs but he does not like it when the denominator grows large. Your task is to help Bert by writing a program that decreases the denominator of a rational number, whilst introducing the smallest error possible. For a rational number A/B, where B > 2 and 0 < A < B, your program needs to identify a rational number C/D such that: 
1. 0 < C < D < B, and 
2. the error |A/B - C/D| is the minimum over all possible values of C and D, and 
3. D is the smallest such positive integer.
Input
The input starts with an integer K (1 <= K <= 1000) that represents the number of cases on a line by itself. Each of the following K lines describes one of the cases and consists of a fraction formatted as two integers, A and B, separated by “/” such that: 
1. B is a 32 bit integer strictly greater than 2, and 
2. 0 < A < B
Output
For each case, the output consists of a fraction on a line by itself. The fraction should be formatted as two integers separated by “/”.
Sample Input
3 
1/4
2/3
13/21
Sample Output
1/3
1/2
8/13

题意:求与给定分数差值最小的分数,保证分数的分母尽可能小。

题解:|A/B-C/D|=min,两边同乘以BD,|AD-BC|=BD*min,已知AB,求CD,问题转换为ax+by=gcd(a,b),求满足条件的x,y。

#include<iostream>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;
int gcd(int a,int b){
    return b?gcd(b,a%b):a;
}
void exgcd(int a,int b,int &d,int &x,int &y){
    if(!b) d=a,x=1,y=0;
    else   exgcd(b,a%b,d,y,x),y-=x*(a/b);
}
int main(){
    int t;scanf("%d",&t);
    while(t--){
        int a,b,x,y;char m;
        scanf("%d%c%d",&a,&m,&b);
        int d=gcd(a,b);
        if(d!=1){
            printf("%d/%d\n",a/d,b/d);
            continue;
        }
        else if(a==1){
            printf("1/%d\n",b-1);
            continue;
        }
        exgcd(a,b,d,x,y);
        int x1,x2,y1,y2;
        x1=(x+b)%b;
        y1=(-y+a)%a;
        x2=(-x+b)%b;
        y2=(y+a)%a;
        if(x1>x2)
            printf("%d/%d\n",y1,x1);
        else
            printf("%d/%d\n",y2,x2);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值