Filling a bookshelf (1)

Professor Oak has b books, each one with width w_(i) and height h_(i),
and he wants to use them to fill a bookshelf as much as possible. For
aesthetic reasons, Prof. Oak wants the second book (if any) to be
shorter than the first book, the third book to be taller than the second
book, …, and the last book to be taller than the penultimate book, so
that the bookshelf has sort of a zigzag look: down, up, down, up, …,
down and up. Note that “short” and “tall” refer to the h_(i)’s, and that
the goal is to maximize the sum of the w_(i)’s of the chosen books.

Please write a program to help Prof. Oak. Take into account that, when
filling the bookshelf, the relative order of the books in the input
cannot be changed.

Input

Input consists of several cases. Each case begins with b, followed by b
pairs with w_(i) and h_(i). Assume 1 ≤ b ≤ 10³ and
1 ≤ w_(i), h_(i) ≤ 10⁹. A special case with b = 0 marks the end of
input.

Output

For every case, print the maximum possible sum of the widths of the
chosen books.

Problem information

Author: Salvador Roura

Generation: 2026-01-25T10:22:42.759Z

© Jutge.org, 2006–2026.
https://jutge.org
