Algorithm: finding the largest list item

Trap: only comparisons between list items are allowed. For example, suppose we have 1,000,000 chess players and we are assigned the task of finding the best chess player in the group. We can play one chess player against any other chess player. Now we want to minimize the maximum number of games that any player plays.

If player A beats player B and B beats C, we can assume that A is better than C. What is the smallest n, so that no player plays more than n games?

@Carl: This is not homework; this is actually the subtask of the larger problem from SPOJ.

+3
source share
4 answers

How to find the largest list item

, ( ) .

, :

Element biggest = list.get(0);
for (Element e : list) {
    if (e.compareWith(biggest) > 0) {
        biggest = e;
    }
}

, , 1 000 000 , . , .

...

№1: . , , , ... .

# 2: ceiling(log2(nos_players)) , . "" / , , , , , ceiling(log2(nos_players)).

:

List players = ...
while (players.size() > 1) {
    List winners = new ArrayList();
    Iterator it = players.iterator();
    while (it.hasNext()) {
        Player p1 = it.next();
        if (it.hasNext()) {
            Player p2 = it.next();
            int result = p1.compareTo(p2);
            if (result < 0) {
                winners.add(p2);
            } else if (result > 0) {
                winners.add(p1);
            } else {
                throw new Exception("draws are impossible in chess");
            }
        } else {
            winners.add(p1); // bye
        }
    }
    players = winners;
}

( : , N 2 ceiling(log2(N)), , 2 . 2 , ceiling(log2(N)) ... , .)

# 2 , , - ; .. . , , A B , A - , B. , , . , , "" , .


, - . , , ( ), .

( ), , . N . , . /, () " " -. , / .

+1

, - .

. , , , - . log n

+9

, , (, ). , , , . .

2 10 : A - , ceil (log 10) = 4

A > B; C > D; E > F; G > H; I > J

A > C; B > E; F > G; D > I

+1

, , ​​ , :

,

, , "".

, , , log n / .

.

  • . , .

    0 <= i < int (n/2) 2i 2i+1.

    i.e., n = 7, int (n/2) = 3, i= 0,1,2; 0 1, 2 3, 4 5.

  • The total number of int (n / 2) indices must be excluded. Subtract this number from n. Then repeat 1 until only one index remains. This will be your biggest.

Here is the implementation in Ruby:

def find_largest(list)

  n = list.size
  working_list = list.clone()

  while n > 1

    temp_list = Array.new()

    for i in (0...n/2)          # remember to cast n/2 to integer if not automatic
      if working_list[2*i] > working_list[2*i+1]
        new_list.push(working_list[2*i])
      else
        new_list.push(working_list[2*i+1])
      end
    end

    working_list = temp_list

    n -= n/2                    # remember to cast n/2 to integer if not automatic

  end

  return working_list[0]

end
+1
source

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


All Articles