The distance between two sets, possibly of different sizes

I have 2 sets of integers, A and B, not necessarily the same size. For my needs, I take the distance between the two elements a and b (integers) only as abs(a-b).

I determine the distance between the two sets as follows:

  • If the sets are the same size, minimize the sum of the distances of all pairs [a, b] (a from A and b from B), minimizing all possible “pair sections” (there are n! Possible sections).
  • If the sets do not have the same size, say A of size m and B of size n, with m <n, then minimize the distance from (1) over all subsets of B whose size is m.

My question is that the following algorithm (just an intuitive assumption) gives the correct answer according to the definition written above.

  • Build a Dsize matrix m X n, withD(i,j) = abs(A(i)-B(j))
  • Find the smallest item D, copy it and delete the row and column of that item. Accumulate the next smallest entry and continue to accumulate until all rows and columns are deleted.

for example, if A={0,1,4}and B={3,4}, that Dis (with elements above and to the left):

3 4

0 3 4

1 2 3

4 1 0

And the distance 0 + 2 = 2emanating from mating 4with 4and 3using 1.

+5
source share
4 answers

, , n m . , , .

, , O (n ^ 3).

, O (n ^ 2) O (n) .

, , , .

O (n ^ 2) :

if (size(B) > size(A))
  swap(A, B);
sort(A);
sort(B);
opt = array(size(B));
nopt = array(size(B));
for (i = 0; i < size(B); i++)
  opt[i] = abs(A[0] - B[i]);
for (i = 1; i < size(A); i++) {
  fill(nopt, infinity);
  for (j = 1; j < size(B); j++) {
    nopt[j] = min(nopt[j - 1], opt[j - 1] + abs(A[i] - B[j]));
  swap(opt, nopt);
}
return opt[size(B) - 1];

i for , opt[j] , {A[0],..., A[i]}, {B[0],..., B[j]}.

, , a1 b1, a2 b2, a1 < a2, b1 <= b2.

+5

, D.

, , . P.

, , OP .

e_k.

A - , B - ( - ).

- B (.. D). e_k - 0.

A B (.. ), . .

+2

. , : A: {3,7} B: {0,4} : {(3,4), (0,7)} 8, {(3,0), (4,7)}, 6.

+1
source

Your answer gives a good approximation to the minimum, but not necessarily the best minimum. You follow the “greedy” approach, which is usually much simpler and gives good results, but cannot guarantee a better answer.

0
source

All Articles