#if __INCLUDE_LEVEL__ void solve() { auto [x, y, a] = input(); auto go = [&](int64_t n) { vector ret; while (n) { ret.push_back(n % a); n /= a; } return ret; }; auto vx = go(x); auto vy = go(y); show(vx); show(vy); vector> f(size(vy) + 1); f[0][1] = 1; for (i : iota(1, ssize(f))) { f[i][0] = 1 + min(vy[i - 1] + f[i - 1][0], vy[i - 1] + 1 + f[i - 1][1]); f[i][1] = 1 + min(a - vy[i - 1] + f[i - 1][0], a - vy[i - 1] - 1 + f[i - 1][1]); } auto eval = [&](auto&& v) { int64_t ret = 0; for (e : v | reverse) { ret *= a; ret += e; } return ret; }; show(f); int64_t ans = abs(x - y); vector memo(ssize(vx) + 1); for (k : iota(0, ssize(memo))) { memo[k] = eval(vx | drop(k)); } for (i : iota(0, ssize(vy) + 1)) { auto vy2 = ALL(vector, vy | drop(i)); for (ty = eval(vy2); int k : iota(0, ssize(vx) + 1)) { ans = min(ans, k + abs(memo[k] - ty) + f[i][0]); } { int j = 0; while (j < ssize(vy2) && vy2[j] + 1 == a) { vy2[j] = 0; ++j; } if (j < ssize(vy2)) { ++vy2[j]; } else { vy2.push_back(1); } } for (ty = eval(vy2); int k : iota(0, ssize(vx) + 1)) { ans = min(ans, k + abs(memo[k] - ty) + f[i][1]); } } print(ans); } #else // __INCLUDE_LEVEL__ #include namespace std { template auto operator>>(istream& is, T&& t) -> decltype(tuple_cat(t), is) { return apply([&is](auto&... xs) -> istream& { return (is >> ... >> xs); }, t); } template auto operator<<(ostream& os, T&& t) -> decltype(tuple_cat(t), os) { auto f = [&os](auto&... xs) -> ostream& { [[maybe_unused]] auto sep = ""; ((os << exchange(sep, " ") << xs), ...); return os; }; return apply(f, t); } template istream& operator>>(istream& is, vector& v) { for (auto&& e : v) { is >> e; } return is; } template ostream& operator<<(ostream& os, const vector& v) { static constexpr auto SEP = is_convertible_v ? " " : "\n"; for (auto sep = ""; const auto& e : v) { os << exchange(sep, SEP) << e; } return os; } } // namespace std template auto input(Args&&... args) { if constexpr (sizeof...(Ts) == 0) { static_assert(sizeof...(Args) == 0); return input(); } else if constexpr (1 < sizeof...(Ts)) { static_assert(sizeof...(Args) == 0); return input>(); } else { using T = std::tuple_element_t<0, std::tuple>; if constexpr (sizeof...(args)) { T x(std::forward(args)...); std::cin >> x; return x; } else { T x; std::cin >> x; return x; } } } template std::array input() { return input>(); } template void print(Ts&&... xs) { std::cout << std::tie(xs...) << '\n'; } using namespace std; #define show(...) static_cast(0) #define for(...) for ([[maybe_unused]] auto&& __VA_ARGS__) #define lambda(...) [&](auto&&... args) { return __VA_ARGS__; } #define $1 get<0>(tie(args...)) #define $2 get<1>(tie(args...)) #define ALL(f, r, ...) lambda(f(begin($1), end($1), ##__VA_ARGS__))(r) namespace std::ranges::views { #include __BASE_FILE__ } // namespace std::ranges::views int main() { ios::sync_with_stdio(false); cin.tie(nullptr); for (_ : views::iota(0, input())) { views::solve(); } } #endif // __INCLUDE_LEVEL__