C. Success Rate
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y.
Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be p / q?
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases.
Each of the next t lines contains four integers x, y, p and q (0 ≤ x ≤ y ≤ 109; 0 ≤ p ≤ q ≤ 109; y > 0; q > 0).
It is guaranteed that p / q is an irreducible fraction.
Hacks. For hacks, an additional constraint of t ≤ 5 must be met.
Output
For each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.
Example
input
4
3 10 1 2
7 14 3 8
20 70 2 7
5 6 1 1
output
4
10
0
-1
Note
In the first example, you have to make 4 successful submissions. Your success rate will be equal to 7 / 14, or 1 / 2.
In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9 / 24, or 3 / 8.
In the third example, there is no need to make any new submissions. Your success rate is already equal to 20 / 70, or 2 / 7.
In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.
你现在的提交成功次数为x,失败次数为y,为了让你的成功比例x/y变为p/q你应该有最少多少次提交(成功和失败的总和),假设成功提交的次数为a,总提交的次数为b,那么使得(x+a)/(y+b) == p/q;即可求这个最下的b,一开始我想到的就是用拓展欧几里得,结果调调搞搞的最后是超时了,后来才知道是利用二分查找,这里我们设一个k使得(x+a)/(y+b) = k*(p/q);故我们只要对k进行二分查找就可以了
完整代码如下:
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const ll INF = 0x7fffffff;
ll x,y,p,q;
ll gcd(ll a,ll b)
{
return b? gcd(b,a%b):a;
}
bool C(ll d){//判断这个d是否符合
if(q*d-y >= 0 && p*d - x >= 0 && p*d-x <= q*d - y)
return true;
return false;
}
int main(void)
{
int T;
cin >> T;
while(T--){
cin >> x >> y >> p >> q;
ll l = 0,r = INF;//注意这里要从0开始
ll ans;
while(r - l > 1){
ll d = (r+l)/2;
if(C(d)) r = d;
else l = d;
}
// cout << l << " " << r << endl;
if(r == INF)
ans = -1;
else
ans = q*r - y;
cout << ans << endl;
}
return 0;
}