Algorithm for finding an object with different weights

We are given N objects, of which exactly one object has a different weight (may be less or more). In addition, we are given M comparisons of the following three types -

  • Weight (Set A) <Weight (Set B)
  • Weight (Set A)> Weight (Set B)
  • Weight (set A) = weight (set B)

Where Set A and Set B (both have the same number of objects) is a list of objects from the original N objects.

Given M such comparisons, I need to find an object with different weights, if possible. Otherwise, say that this list of comparisons M is not enough to detect one with the other weight.

Can someone suggest an algorithm to solve this problem?

+4
source share
3 answers

, , , , .

, , ( ). :

  • A < B: B.
  • A > B: B.
  • A = B: B.

, .. , - , , - , :

  • solution = null, noFlagSolution = null, noFlagCount = 0.

  • :

    • : continue.
    • : noFlagSolution = current, noFlagCount++
    • :
      • solution != null: return null ( ).
      • Else: solution = current
  • solution != null: return solution ( , ).

  • noFlagCount == 1: return noFlagSolution ( , , , ).

  • .

0

2N - 1 , 1 , 2 , 2 ,..., N , N . , . , ( , i, ), . , . .

0

, , ceil (log3 (N)).

, . , 3- . , , , , . , , . , log3 (N), N 3, , N.

If you do not know if an object of different weights is heavier or lighter than the rest, then it takes about log3 / 2 (N), since in the worst case you can throw out only one of the three piles, thereby reducing the number of objects in two times.

0
source

Source: https://habr.com/ru/post/1682069/


All Articles