#include int output = 0; // finds the absolute value of an input |(input)| int getAbs(int input) { if (input < 0) { return (0 - input); } return input; } int nextLayer(int start, int dest, int current, int max, int lim){ int operations[5] = {0}; if(start == dest){ output = current; return 0; } if(current < max){ operations[0] = nextLayer(start+1, dest, current + 1, max, lim); operations[1] = nextLayer(start-1, dest, current + 1, max, lim); operations[2] = nextLayer(start*5, dest, current + 1, max, lim); if(start % 3 == 0){ operations[3] = nextLayer(start/3, dest, current + 1, max, lim); } if(start % 2 == 0){ operations[4] = nextLayer(start/2, dest, current + 1, max, lim); } } int min = lim; for (int i = 0; i < 5; i++) { if (min > operations[i]) { min = operations[i]; } } if(min > 0){ return min; } else { return output; } } int main(int argc, char *argv[]){ // declaration and scanning int start, dest; scanf("%d %d", &start, &dest); // maximum theoretical number of steps, as you can +1 or -1 till one reaches the result int lim = getAbs(start - dest); // to avoid simply passing lim and cause a CPU limit, this for loops will make it // go one depth at a time. Otherwise it would be a depth-first algorithm and will cause // trouble int nsol = 0; for (int i = 2; i < lim; i++){ nsol = nextLayer(start, dest, 1, i, lim, 0); if (nsol) { break; } } printf("%d\n", nsol-1); }