思路:
假设要进行p次正确提交,q-p次非正确提交, 则 (a+p)/(b+q) == c/d
由题意知c、d互质,所以 (a+p)/(b+q)应该是 c/d的非最简分数或最简分数, 即 (a+p)/(b+q) == nc/nd , 其中 0<=p<=q n>=1 且都是整数
所以 p = nc-a, q = nd-b p、q都是n的递增函数, 所以二分n寻找最小的n满足条件,无满足输出-1
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t--)
{
int a, b, c, d;
cin >> a >> b >> c >> d;
LL l = 1, r = 1e9;
LL ans = -1;
while(l<=r)
{
LL mid = (l+r) >> 1;
//cout << mid << endl;
LL p = mid*c-a, q = mid*d-b;
if(p>=0 && q>=0 && p<=q)
{
r = mid-1;
ans = q;
}
else
l = mid+1;
}
cout << ans << endl;
}
return 0;
}