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

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 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 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
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 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;
			}
			else
			l=mid+1;
		}
		if(ans==-1)
		printf("-1\n");
		else
		printf("%lld\n",ans*q-y);
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值