昨天校赛的C题... 这题导致我的比赛从15分钟就提前结束了。。。昨天确实没想清楚,虽想到了逼近的方法,但是没有理解透彻,采用的是暴力逼近,其实再仔细想一下,对于最值有影响的点就几个而已。。 。
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll ex_gcd(ll a,ll b,ll &x,ll &y)
{
if(b==0)
{
x=1;y=0;
return a;
}
else
{
ll ret=ex_gcd(b,a%b,x,y);
ll t=x;
x=y;
y=t-(a/b)*y;
return ret;
}
}
ll count(ll x,ll y)
{
if(x*y<=0)
{
return fabs(x)+fabs(y);
}
else
{
return max(fabs(x),fabs(y));
}
}
int main()
{
ll A,B,a,b,x,y,xx,yy,g,ans,tmp;
int t;
cin>>t;
while(t--)
{
cin>>A>>B>>a>>b;
g=ex_gcd(a,b,x,y);
if((B-A)%g!=0)
{
cout<<-1<<endl;
continue;
}
x*=(B-A)/g;y*=(B-A)/g;
ans=-1;
//case 1: 把x逼近0
tmp=x/(b/g);
xx=x-tmp*(b/g);
yy=y+tmp*(a/g);
ans=(ans==-1)?count(xx,yy):min(ans,count(xx,yy));
//case 2:把y逼近0
tmp=y/(a/g);
xx=x+tmp*(b/g);
yy=y-tmp*(a/g);
ans=(ans==-1)?count(xx,yy):min(ans,count(xx,yy));
//case 3:把x逼近y且不超过y
tmp=(y-x)/(a/g+b/g);
xx=x+tmp*(b/g);
yy=y-tmp*(a/g);
ans=(ans==-1)?count(xx,yy):min(ans,count(xx,yy));
//case 4:把x逼近y且超过y
tmp++;
xx=x+tmp*(b/g);
yy=y-tmp*(a/g);
ans=(ans==-1)?count(xx,yy):min(ans,count(xx,yy));
tmp-=2;
xx=x+tmp*(b/g);
yy=y-tmp*(a/g);
ans=(ans==-1)?count(xx,yy):min(ans,count(xx,yy));
cout<<ans<<endl;
}
return 0;
}