#include #include #include #include using namespace std; typedef long long ll; template struct Graph { public: using value_type = T; struct Edge { int from, to; T cost; int id; operator int() const { return to; } }; Graph() {} Graph(int n) : n(n), m(0), g(n) {} void add_directed_edge(int from, int to, T cost = 1) { assert(0 <= from && from < n); assert(0 <= to && to < n); g[from].push_back((Edge){from, to, cost, m++}); } void add_undirected_edge(int from, int to, T cost = 1) { assert(0 <= from && from < n); assert(0 <= to && to < n); g[from].push_back((Edge){from, to, cost, m}); g[to].push_back((Edge){to, from, cost, m++}); } int size() { return n; } int edge_size() { return m; } inline const std::vector &operator[](const int &u) const { return g[u]; } inline std::vector &operator[](const int &u) { return g[u]; } private: int n, m; std::vector> g; }; template std::vector dijkstra(GRAPH &g, int s) { using T = typename GRAPH::value_type; using P = std::pair; int n = g.size(); assert(s >= 0 && s < n); std::vector d(n, -1); std::priority_queue, std::greater

> que; d[s] = 0; que.push(P(0, s)); while (que.size()) { auto [dist, u] = que.top(); que.pop(); if (d[u] < dist) { continue; } for (auto e : g[u]) { int v = e.to; if (d[v] == -1 || d[v] > d[u] + e.cost) { d[v] = d[u] + e.cost; que.push(P(d[v], v)); } } } return d; } int main() { int t; cin >> t; while (t--) { ll x, y, a; cin >> x >> y >> a; ll z = y; ll p = x, q = y; Graph g(100); map mp; int r[200]; int k = 0; if (!mp.count(x)) { r[k] = x; mp[x] = k++; } if (!mp.count(y)) { r[k] = y; mp[y] = k++; } if (!mp.count(y + 1)) { r[k] = y + 1; mp[y + 1] = k++; } while (x || y) { if (x <= y) { g.add_directed_edge(mp[x], mp[y], y - x); y /= a; if (!mp.count(y)) { r[k] = y; mp[y] = k++; } if (!mp.count(y + 1)) { r[k] = y + 1; mp[y + 1] = k++; } } else { g.add_directed_edge(mp[x], mp[y + 1], x - (y + 1)); if (!mp.count(x / a)) { r[k] = x / a; mp[x / a] = k++; } g.add_directed_edge(mp[x], mp[x / a], 1); x /= a; } } while (true) { ll w = z / a; g.add_directed_edge(mp[z], mp[z + 1], 1); g.add_directed_edge(mp[z + 1], mp[z], 1); g.add_directed_edge(mp[w], mp[z], z - w * a + 1); g.add_directed_edge(mp[w + 1], mp[z + 1], (w + 1) * a - (z + 1) + 1); if (z >= w + a) { g.add_directed_edge(mp[z], mp[w + 1], z - (w + 1)); g.add_directed_edge(mp[w + 1], mp[z], z - (w + 1)); } if (z >= (w / a + 1) * a) { g.add_directed_edge(mp[w / a + 1], mp[z], z - (w / a + 1) * a + 1); } if (!z) { break; } z = w; } vector d = dijkstra(g, mp[p]); cout << d[mp[q]] << endl; } }