(Java)
M题 (补题,思路源自于出题人题解)
题目为喝水x,两杯水可以有和,也可以有差,问至少几次操作。有x' +A,+B,+(A-B),+(B-A),四种喝水情况,最优解显然为固定整数AB经过至少r,s构成x
有rA+sB=gcd(A,B)(r>=0或s>=0.gcd>=1)
(裴蜀定理)(若gcd不整除x,则无解(x=-1))
(可以以扩展欧几里得法求r,s)
若rs>0,则为2(r+s),因为倒水喝水各一次操作
若rs<0,设其中的r>0,s<0,意味着rA>sB(rA-|s|B>=1),那么r次倒水A并s次倒掉水b,且由于严格大于,次数还可减一,A杯余水小于b时可以省去s次操作,同样A(正数)倒水喝水各一次操作
故为2(r-s)-1
推广开,则为2|r-s|-1
然后从原点开始搜索A,B,由欧几里得算法,每组复杂度logx
(提解说次数求2|r-s|-1和2(r+s)的最大值,但rs都正时右边必大,存在负时左边必大,个人感觉没有必要求max)
扩展欧几里得法:由a,b时,a=0,b=gcd,gcd=0a+1b反推x,y
import java.util.Scanner;
public class Main {
static long inf = (long) 1e18;
public static void exgcd(long a, long b, long[] res) {
if (b == 0) {
res[0] = a;
res[1] = 1;
res[2] = 0;
} else {
exgcd(b, a % b, res);
long x = res[1];
long y = res[2];
res[1] = y;
res[2] = x - (a / b) * y;
}
}
public static long wk(Scanner scanner) {
long a = scanner.nextLong();
long b = scanner.nextLong();
long c = scanner.nextLong();
long[] res = new long[3];
exgcd(a, b, res);
long g = res[0];
long x = res[1];
long y = res[2];
if (c % g != 0) {
return -1;
}
a /= g;
b /= g;
c /= g;
x *= c;
y *= c;
long ans = inf;
// 附近找最小值
long t0 = -x / b;
for (long t = t0 - 1; t <= t0 + 1; ++t) {
ans = wkHelper(t, a, b, x, y, ans);
}
t0 = y / a;
for (long t = t0 - 1; t <= t0 + 1; ++t) {
ans = wkHelper(t, a, b, x, y, ans);
}
return ans == inf ? -1 : ans;
}
private static long wkHelper(long t, long a, long b, long x, long y, long ans) {
long r = x + b * t;
long s = y - a * t;
if (r >= 0 && s >= 0) {
ans = Math.min(ans, 2 * (r + s));
} else {
ans = Math.min(ans, 2 * (Math.abs(r) + Math.abs(s)) - 1);
}
return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int T = scanner.nextInt();
while (T-- >= 0) {
System.out.println(wk(scanner));
}
scanner.close();
}
}