开发者

The shortest path between two integers by adding or subtracting

开发者 https://www.devze.com 2023-04-02 05:48 出处:网络
Here\'s the description of this problem: You are given two integers a and b.You want to find the shortest sequence of operations necessary to transform a into b, where at each step you are allowed t

Here's the description of this problem:

You are given two integers a and b. You want to find the shortest sequence of operations necessary to transform a into b, where at each step you are allowed to add or subtra开发者_JAVA百科ct 5, 7, or 12.

For example, if you are given a = -5 and b = 19, the shortest path is

-5 + 12 + 12 = 19

If you were given 1 and 3, the shortest path would be

1 + 7 - 5 = 2

The only way I can think about solving this is using BFS and maybe some more pruning. Is there a better algorithm I could use instead?

Thanks!


Let's start off with a set of interesting observations. As many others have noted, the goal is to find some linear combination 5x + 7y + 12z = b - a with integer coefficients such that |x| + |y| + |z| is minimized. But there are some very interesting connections between these three numbers that we can exploit:

  1. If we ever have a combination 5x + 7y + 12z where x and y are both positive or both negative, we can cancel out some number of x's and y's to add an equivalent number of 12s. In other words, no optimal solution has the same sign on both x and y, because we could always make this solution better.
  2. If we ever have a combination 5x + 7y + 12z where y and z have opposite signs, we can always remove a 7 and 12 and add in a 5 of the appropriate sign to get a better solution. Similarly, if x and z have opposite signs, we can always remove a 5 and 12 and add a 7 of the appropriate sign. This means that we never need to consider any solution where z has the same sign as either x or y, because it means that there would have to be a better solution.

Let's think about what (1) and (2) collectively tell us. (1) says that the signs on x and y can't be the same, since we can always do better. (2) says that if x and z have opposite signs or if y and z have opposite signs, we can always do better. Collectively this means that

Lemma: At least one of x, y, or z must be zero in the optimal solution.

To see this, if all three are nonzero, if x and y have the same sign, then we can clearly make the solution better by replacing them with 12s. Otherwise, x and y have opposite signs. Thus if x and z have different signs, by (2) we can replace them with fewer 7's, otherwise y and z have different signs and by (2) we can replace them with fewer 5's.

Okay, this is looking really great! This means that we just need to solve these three integer equations and find which one has the smallest sum of coefficients:

  • 5x + 7y = b - a
  • 5x + 12z = b - a
  • 7y + 12z = b - a

Fortunately, by Bezout's identity, because gcd(5, 7) = gcd(5, 12) = gcd(7, 12) = 1, all of these systems of equations have a solution for any value of b - a.

Now, let's see how to solve each of these equations. Fortunately, we can use some cute tricks to greatly reduce our search space. For example, for 5x + 7y = b - a, the value of x can't be outside of [-6, +6], since if it were we could just replace seven of the 5's with five 7's. This means that we can solve the above equation by doing the following:

For x = -6 to +6, see if 5x + 7y = b - a has an integer solution by computing (b - a) - 5x and seeing if it's divisible by seven. If so, the number of steps required to solve the problem is given by |x| + |((b - a) - 5x) / 7|.

We can use similar tricks to solve the latter two equations - for the second equation, x ranges from -11 to +11, and for the third y ranges from -11 to +11 as well. We can then just take the best answer out of all three equations to see what the answer is.

Here's some pseudocode to record the fewest number of steps possible. This can easily be modified to return what those steps are by just recording which of the solutions was used and then expanding it out into a full path:

Let best = infinity

# Solve 5x + 7y = b - a
for x = -6 to +6:
    if ((b - a) - 5 * x) mod 7 = 0:
        best = min(best, |x| + |((b - a) - 5 * x) / 7|)

# Solve 5x + 12y = b - a
for x = -11 to +11:
    if ((b - a) - 5 * x) mod 12 = 0:
        best = min(best, |x| + |((b - a) - 5 * x) / 12|)

# Solve 7x + 12y = b - a
for x = -11 to +11:
    if ((b - a) - 7 * x) mod 12 = 0:
        best = min(best, |x| + |((b - a) - 7 * x) / 12|)

return best;

This algorithm is amazingly fast - it runs in O(1) time because the number of iterations required to solve each three of the linear systems is a constant (at most 23). It requires only O(1) memory to hold the possible values, and I think that in practice it's probably the fastest algorithm you'll be able to write.

Hope this helps!


The problem is equivalent to getting the number a-b. Or abs(a-b), since it's symmetric around zero. I think this can be done easily with an adoption of dynamic programming. For example, to quickest way to get 23 is the quickest way to get 23+5,23-5,23+7,23-7,23+12 or 23-12 plus one operation. If you apply that a couple of times on the start condition (cost of +5,-5,.. is 1, others are infinite), you'll have your answer in O(a-b).


You need to solve 5x+7y+12z = b-a. such that |x| + |y| + |z| is minimum. Perhaps there is a straightforward mathematical way. Perhaps this helps: Link


I guess you could have a look at the Subset Sum Problem for ideas.


Pre calculate the operations needed for the first minimum range, after that just keep adding multiples of +12.


Pre-calculate all your operations combos into a hash map then just do a look-up on the answer.

The pre-calculation step will take time but once its done you have finds for answers within the pre-calculated range that are 1 look-up operation.

Here is a small JavaScript demonstration:

// maximum depth of combos to try
var MAX = 6;
// possible operations
var ops = ["+-5", "+5", "+-7", "+7", "+-12", "+12"];
// initial hash map of operations->value
var all = {"+5":5, "+-5":-5, "+7":7, "+-7":-7, "+12":12, "+-12":-12};
var allcnt = 6; // count combos *not needed*
// initial hash map of values->operations, plus "0" so we can avoid it
var unique = {"0": "0", "5":"+5", "-5":"+-5", "7":"+7", "-7":"+-7", "12":"+12", "-12":"+-12" };
var ready = false;
// get all useful combinations of ops
function precalc() {
  var items = [];
  for(var p in all) {
     items.push(p);
  }
  for(var p=0; p<items.length; p++) {
    for(var i=0; i<ops.length; i++) {
      var k = items[p] + ops[i];
      var v = eval(k);
      if(unique[v] == null) {
        unique[v] = k;
        all[k] = v;
        allcnt++;
      }
    }
  }
}
// find an answer within the pre-calc'd depth
function find(a, b) {
  if(ready === false) {
    for(var i=0; i<MAX; i++) precalc();
    ready = true;
  }
  return unique[""+Math.abs(a-b)];
}
// test
find(-5,19);
0

精彩评论

暂无评论...
验证码 换一张
取 消