problems / 159

Fence Posts From Scrap Rods

medium backtracking bitmask dp sorting 2000 ms · 256 MB

Fence Posts From Scrap Rods

A carpenter is clearing out the workshop. In the scrap bin there are n wooden rods with integer lengths a_1, a_2, …, a_n. A customer wants exactly k fence posts, and every post must have the same length.

A post is made by gluing one or more whole rods end to end, so its length is the sum of the lengths of its rods. The carpenter follows these rules:

  • every rod in the bin goes into exactly one post: nothing is left over and nothing is used twice;
  • rods are never cut, shortened or overlapped;
  • exactly k posts are made, each from at least one rod, and all k posts have the same length. That length can be anything; it isn't given in advance.

For each bin, decide whether the carpenter can do this.

Input

The first line contains T (1 ≤ T ≤ 100), the number of bins.

Each bin is described by two lines. The first contains n and k (1 ≤ k ≤ n ≤ 16). The second contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^9), the rod lengths.

Output

For each bin, print YES on its own line if the rods can be glued into k posts of equal length using every rod exactly once, and NO otherwise.

Notes

In the first example, the first bin can be glued into four posts of length 5: 5, 4 + 1, 3 + 2 and 3 + 2. In the second bin the rods total 10, which can't be split into three equal whole lengths. In the third bin the posts would have to be 6 long, but no two of the three rods of length 4 can share a post, and only the rods 2 and 1 are short enough to join a 4.

In the second example, the first bin works as 3 + 3 and 2 + 2 + 2; the second as 5 + 3 + 2 and 4 + 3 + 3.

The total length of the rods can exceed 2^31.

Example 1

Input

3
7 4
4 3 2 3 5 2 1
4 3
1 2 3 4
6 3
4 4 4 3 2 1

Output

YES
NO
NO

Example 2

Input

5
5 2
3 3 2 2 2
6 2
5 4 3 3 3 2
1 1
7
3 3
2 2 2
3 3
2 2 3

Output

YES
YES
YES
YES
NO

Hints · reveal one at a time if you're stuck

Hint 1

Every post must have the same length, and the total length is fixed, so that common length is forced. Before searching, which quick checks rule out most bins?

Hint 2

Greedy choices fail on small examples, so think about searching over which rods have been used. With at most 16 rods, a bitmask of used rods can be the state, and the length already placed on the post being built is determined by that mask alone.

Hint 3

So you only need to know, for each mask, whether its rods can be laid out validly. Work out when adding one more unused rod keeps the layout valid; about n·2^n steps is fast enough. Keep sums in 64-bit integers.

report an issue Prefer your own editor? sooks prep 159 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.