转自:http://blog.csdn.net/llzhh/article/details/71480809
看别人博客看了挺久,才知道二分的东西是别的。这样二分也是满足单调性的,而且看起来很好写。。。
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
#define sf scanf
#define pf printf
#define mem(a,b) memset(a,b,sizeof(a));
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define LL long long
#define INF 10000000000
LL x,y,p,q;
bool ok(LL t){
if(t*p-x<=q*t-y&&t*p-x>=0&&t*q-y>=0)return true;
else return false;
}
int main(){
int T;
sf("%d",&T);
while(T--){
cin>>x>>y>>p>>q;
LL l=0,r=INF;
LL flag=-1;
while(l<r){
LL mid=(l+r)/2;
if(ok(mid))r=mid,flag=0;//表示有过符合的,那么就会有解,
else l=mid+1;
}
if(flag==-1)cout<<-1<<endl;
else cout<<l*q-y<<endl;
}
}