Garden Fence

Time limit5sMemory limit128 MB

Summary
Choose a line through two boundary points splitting the field into two sides; minimize the total value of trees cut down.
Level

Hard8 of 10

Topics
Geometry, Sorting, Math
Solved
No attempts yet

Problem

Gary is a careful gardener who owns a rectangular field full of trees. Two kinds of trees grow on his land: pines and larches. To improve their health he wants to switch from a generic fertilizer to a specialized fertilizer for each kind of tree.

Because there are so many trees, the fertilizer cannot be applied to each tree individually. Instead, Gary will build a fence that splits the field into two parts, apply the pine fertilizer on one side and the larch fertilizer on the other. The fence is built along a straight line connecting two distinct points on the boundary of the field.

Each fertilizer is ideal for its intended tree but lethal to the other kind. After the fence is built and a fertilizer is assigned to each side, every larch on the pines' side and every pine on the larches' side must be cut down to avoid a slow decline that would ruin the landscape. In addition, before the fence can be built, any tree of either kind lying exactly on the fence line must be cut down.

Every tree has a value that depends on its kind, age, and other factors. Gary wants to choose the fence line and the fertilizer assignment so that his loss — the total value of all trees that are cut down — is as small as possible.

Given the trees, report the minimum possible loss.

Input

The input contains several test cases.

Each test case begins with a line containing two integers PP and LL, the number of pines and the number of larches (1≤P,L≤10001 \le P, L \le 1000). Each of the next PP lines describes a pine, and each of the following LL lines describes a larch.

Each tree is a point in the plane described by three integers XX, YY, and VV: its coordinates (−105≤X,Y≤105-10^5 \le X, Y \le 10^5) and its value (1≤V≤10001 \le V \le 1000). Within a single test case, no two trees share the same location.

The input ends with a line containing two zeros, which must not be processed.

Output

For each test case, output a single line containing one integer: the minimum possible loss.

Examples1

  1. Example 1

    Input
    2 3
    2 2 10
    4 4 10
    2 4 10
    4 2 10
    3 3 10
    2 3
    2 2 20
    4 4 20
    2 4 10
    4 2 10
    3 3 10
    1 1
    -10000 -10000 1000
    10000 10000 1000
    2 2
    0 0 4
    0 2 2
    0 1 3
    0 4 1
    4 1
    0 1 1000
    0 -1 1000
    1 0 1000
    -1 0 1000
    0 0 1
    0 0
    
    Expected output
    10
    20
    0
    2
    1