cf807 c 二分好题

能够二分判定的前提是能找到一个单调关系,有时候需要将不是单调关系的数据转换成另外的具有单调关系的数据

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
ll t,x,y,p,q;
int judge(ll m){
    ll a=m*p-x,b=m*q-y;
    if(a>=0 && b>=0 && a<=b)
        return 1;
    return 0;
}
int main(){
    cin >> t;
    while(t--){
        cin >> x >> y>> p>>q;
        ll l=0,r=1000000000,mid,ans=-1;
        if(x==y && p==q){
            puts("0");
            continue;
        }
        if(p==q && x!=y){
            puts("-1");
            continue;
        }
        while(l<=r){
            mid=l+r>>1;
            if(judge(mid))
                ans=mid,r=mid-1;
            else l=mid+1;
        }
        if(ans==-1) cout << -1 << endl;
        else printf("%lld\n",ans*q-y);
    }
} 

猜你喜欢

转载自www.cnblogs.com/zsben991126/p/10243427.html