解題思路
不逐步倒水就求巨大容器的最少操作數。
最短非平凡解可省去立即抵消的裝滿倒空,並固定一個倒水方向;兩種方向皆檢查。容量除以gcd後互質,目標也須能被原gcd整除且不大於最大容量。
對方向a倒到b,令n為來源裝滿次數、m為目標倒空次數。終點來源空時有na−mb=z且z<b;終點目標滿時有na−mb=z+b且z<a。每種情況的操作數都是2(n+m),包含n次裝滿、m次倒空及n+m次倒水。
由na≡z mod b以模反元素求n的最小正同餘解,再提高n到使m≥0的最小值。較大的同餘解會同時增加n與m,故不能更優。檢查兩種終態、兩方向,另處理直接裝滿即可得到z的1步情況。
每筆 O(log min(x,y))次大整數歐幾里得操作,額外空間為整數位數;不依答案動作數逐次模擬。
Step-by-step animation
容量5、3量出4的最短6步
步驟 1 / 3
步驟 1
x=5,y=3,z=4,考慮5倒入3。
裝滿來源次數n
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
cpp_int gc(cpp_int a, cpp_int b) {
while (b != 0) {
cpp_int r = a % b;
a = b;
b = r;
}
return a;
}
cpp_int inv(cpp_int a, cpp_int m) {
cpp_int b = m, x = 1, y = 0;
while (b != 0) {
cpp_int q = a / b, r = a - q * b;
a = b;
b = r;
r = x - q * y;
x = y;
y = r;
}
x %= m;
if (x < 0)
x += m;
return x;
}
cpp_int ceildiv(cpp_int a, cpp_int b) {
return (a + b - 1) / b;
}
int main() {
int q;
cin >> q;
while (q--) {
cpp_int x, y, z;
cin >> x >> y >> z;
if (x <= 0 || y <= 0 || z <= 0 || z > max(x, y)) {
cout << -1 << '\n';
continue;
}
cpp_int g = gc(x, y);
if (z % g != 0) {
cout << -1 << '\n';
continue;
}
x /= g;
y /= g;
z /= g;
if (z == x || z == y) {
cout << 1 << '\n';
continue;
}
cpp_int best = -1;
for (int dir = 0; dir < 2; dir++) {
cpp_int a = dir ? y : x, b = dir ? x : y;
cpp_int n0 = b == 1 ? cpp_int(1) : cpp_int((z * inv(a % b, b)) % b);
if (n0 == 0)
n0 = b;
for (int mode = 0; mode < 2; mode++) {
if ((mode == 0 && z >= b) || (mode == 1 && z >= a))
continue;
cpp_int target = z;
if (mode)
target += b;
cpp_int n = n0, need = ceildiv(target, a);
if (n < need)
n += ceildiv(need - n, b) * b;
cpp_int m = (n * a - target) / b, steps = 2 * (n + m);
if (best < 0 || steps < best)
best = steps;
}
}
cout << best << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。