773A - Success Rate(数学+二分)

https://codeforces.com/problemset/problem/773/A


思路:

开始的时候转化成了 

(x+f)/(y+t)=p/q----->q*(x+f)==(y+t)*p--->然后拆开,同时还有一个t>=f的式子。但是前者拆开之后要求一个最小的p的倍数满足分子,二分也不好搞。

考虑到p,q互质,所以(x+f)=k1*p;(y+t)=k2*q;k1==k2--->  两个式子{ f=k*p-x;  t=k*q-y}单调性明显,可以二分了。

注意二分随意check容易溢出,要不128,要不大致计算一下上界。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
bool check(LL k,LL x,LL y,LL p,LL q){
    LL cnt=k*p-x;
    return cnt>=0&&k*q-y>=cnt;
}
int main(void){
   cin.tie(0);std::ios::sync_with_stdio(false);
   LL t;cin>>t;
   while(t--){
     LL x,y,p,q;cin>>x>>y>>p>>q;
     LL l=0;LL r=1e10;///太大溢出
     while(l<r){
        LL mid=(l+r)>>1;
        if( check(mid,x,y,p,q)==true ) r=mid;
        else l=mid+1;
     }
     if(l>=1e10){
        cout<<"-1"<<"\n";
     }
     else cout<<l*q-y<<"\n";
   }
   return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/115336909