[BZOJ2187][类欧几里得算法]fraction

题意

求p,q满足 ab<pq<cd 的解


推一发

ab+1cd1ab+1

a=0pq<cdq>dpc
因为q要求最小
p=1,q=dc

a<=b and c<=ddc<qp<ba

Else a%bb<pqab<cdab

#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>

using namespace std;

typedef long long ll;
typedef pair<ll,ll> pairs;

ll a,b,c,d,g;

ll gcd(ll a,ll b){
    return b?gcd(b,a%b):a;
}

inline void simplify(ll &a,ll &b){
    ll g=gcd(a,b); a/=g; b/=g;
}

pairs solve(ll p1,ll q1,ll p2,ll q2){
    simplify(p1,q1); simplify(p2,q2);
    ll a=p1/q1+1,b=(ll)ceil((double)p2/q2)-1;
    if(a<=b) return pairs(a,1);
    if(p1==0) return pairs(1,(ll)(q2/p2)+1);
    if(p1<=q1&&p2<=q2){
        pairs r=solve(q2,p2,q1,p1);
        swap(r.first,r.second);
        return r;
    }
    ll t=p1/q1;
    pairs r=solve(p1%q1,q1,p2-t*q2,q2);
    r.first+=r.second*t;
    return r;
}

int main(){
    while(~scanf("%lld%lld%lld%lld",&a,&b,&c,&d)){
        pairs Ans=solve(a,b,c,d);
        printf("%lld/%lld\n",Ans.first,Ans.second);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值