PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#QHD0000095. Tạ đĩa gần 1000 kg (Walrus Weights)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tạ đĩa gần 1000 kg (Walrus Weights)

Walrus Weights

Source: Kattis

Version: Phuoc Hung OJ Extended

Problem Statement

Wallace the walrus is training to lift exactly 10001000 kilograms. He has nn separate weight plates, indexed from 11 to nn. Plate ii has a positive integer weight wiw_i. He may choose any subset of the plates, and each plate can be chosen at most once. Even if two plates weigh the same, they are distinct physical plates. The empty selection is allowed, with total weight zero.

For a selection with total weight SS, Wallace wants to minimize ∣S−1000∣|S-1000|. If two different reachable totals have the same minimum distance, he must take the larger total. For example, if totals 998998 and 10021002 are both reachable and no closer total exists, the answer is 10021002.

Find the best total weight, not the indices of the selected plates.

Input

  • The first line contains one integer nn, the number of plates.
  • Each of the next nn lines contains one positive integer wiw_i, the weight of plate ii.

Output

Output the attainable integer total SS closest to 10001000; on a tie, output the larger total.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le20 and 1≤wi≤501\le w_i\le50 for every ii.
  • Subtask 2 (30 points): 1≤n≤1201\le n\le120 and 1≤wi≤10001\le w_i\le1000 for every ii.
  • Subtask 3 (50 points): 1≤n≤9991\le n\le999 and 1≤wi≤10001\le w_i\le1000 for every ii.

Examples

Example 1

Input

4
900
500
498
4

Output

1002

Explanation: Plates weighing 500500, 498498, and 44 give total 10021002, two units above the goal. The pair 500500, 498498 gives 998998, two units below it. Since the distances tie, Wallace chooses 10021002. There is no attainable total closer than two units.

Example 2

Input

1
1

Output

1

Explanation: The only attainable totals are 00 and 11; the latter is closer to 10001000.