Codeforces Round #412 C. Success Rate (二分查找)

来源:互联网 发布:淘宝蛋糕店 编辑:程序博客网 时间:2024/06/15 20:49
C. Success Rate
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have madey submissions, out of whichx have been successful. Thus, your current success rate on Codeforces is equal tox / y.

Your favorite rational number in the [0;1] range isp / q. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to bep / 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 integersx,y,p andq (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 oft ≤ 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
43 10 1 27 14 3 820 70 2 75 6 1 1
Output
4100-1
Note

In the first example, you have to make 4 successful submissions. Your success rate will be equal to7 / 14, or1 / 2.

In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to9 / 24, or3 / 8.

In the third example, there is no need to make any new submissions. Your success rate is already equal to20 / 70, or2 / 7.

In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1.



题意:有y个任务已经成功了x个,问还需要至少多少个任务,才能让成功率等于 p/q;


分析:假设至少需要b个任务,成功a个可以达成 (x+a)/(y+b)=(p/q)。

因为 p和q互质  所以  x+a=n*p     y+b=n*q

所以a=n*p-x    b=n*q-y

又因为 (a<b)  (p<q) (x<y)

所以当n增大的时候 a和b都是增大的。我们需要找的是满足 a<=b 并且 b尽量小

所以二分查找就可以了

注意a和b要开long long。

AC代码:

#include<stdio.h>#include<string.h>int main(){int T;scanf("%d",&T);while(T--){long long x,y,p,q;scanf("%lld%lld%lld%lld",&x,&y,&p,&q);long long ans=-1;long long l=0,r=1e9;while(l<=r){long long mid=(l+r)>>1;long long a=mid*p-x,b=mid*q-y;if(a>=0&&b>=0&&a<=b){ans=mid;r=mid-1;}elsel=mid+1;}if(ans==-1)printf("-1\n");elseprintf("%lld\n",ans*q-y);}}

0 0
原创粉丝点击