Problem Statement:
We are given three positive integers $x$, $y$, and $k$, and our aim is to convert $x$ to $y$ in the minimum number of steps using one of the following two operations at each step:
- Multiply $x$ by $k$
- Subtract $1$ from $x$
Let convert($x$,$y$,$k$) be the minimum number of steps to convert $x$ to $y$ using $k$. Then find the values for the following:
- convert(3,10,2)
- convert(4,92,3)
- convert(11,104250,2)
Note: Following are the official answers for the three parts mentioned above:
- 3
- 7
- 24
My Approach: I think it is easier to go the other way round, i.e., to convert $y$ to $x$ using the opposite operations, which is to divide by $k$ or add $1$ at each step. I think this is easier because it restricts the possible cases as division is possible only when the number is a multiple of k. And while doing this we can avoid repeated calculations in case we encounter the same number some time later. For example, for convert(3,10,2), we have this,
I even coded a Breadth First Search solution for this problem (thought it is not so useful as the question was asked in a pen and paper based exam):
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 1e16;
int main() {
const int lim = 10000;
int t;
cin >> t;
while(t--) {
ll x, y, k;
cin >> x >> y >> k;
map<ll,bool> vis;
map<ll,int> dist;
queue<ll> q;
q.push(y);
vis[y] = true;
bool found = false;
while(!q.empty()) {
int u = q.front();
q.pop();
if(u == x) {
found = true;
break;
}
if(dist[u] < lim) {
if(u+1<INF && !vis[u+1]) {
vis[u+1] = true;
dist[u+1] = 1+dist[u];
q.push(u+1);
}
if(u%k == 0 && !vis[u/k]) {
vis[u/k] = true;
dist[u/k] = 1+dist[u];
q.push(u/k);
}
}
}
if(found) cout << dist[x] << "\n";
else cout << "-1\n";
}
return 0;
}
So my question is:
Can we do something better than to look through each possibility? Any observations that can help? I am looking for an answer that can help compute the values without the help of a computer.
(Fill in the gaps as needed. You should have everything that you need listed out here.)
Observations:
For example, in the first case,
And for the last case,