luogu#P5167. xtq 的神笔

xtq 的神笔

Background

When xtq was in fourth grade, he got a set of magical paintbrushes. To test how powerful the brushes were (and to show off his strong artistic talent), he decided to copy several paintings for his art teacher.

Problem Description

The shape of each painting can be abstracted as nn cells in a row, where the ii-th cell has a weight aia_i.

xtq has enough paintbrushes of different colors. Each time he uses one brush, he can paint a continuous segment on the cells with length at least kk, and then switch to another brush and continue painting starting from the next cell, where k<nk<n.

To test xtq’s painting skills, the art teacher sets some challenges.

He may start painting from any cell between 11 and kk (inclusive) and paint all the way to cell nn. If he starts from cell ii, he gains an initial score of bib_i.

Suppose xtq uses the same brush to paint continuously from cell ii to cell jj. Then he gains a score of $(a_i \mathbin{\mathrm{or}} a_{i+1} \mathbin{\mathrm{or}} a_{i+2} \mathbin{\mathrm{or}} \cdots \mathbin{\mathrm{or}} a_j) + (a_i \mathbin{\mathrm{and}} a_{i+1} \mathbin{\mathrm{and}} a_{i+2} \mathbin{\mathrm{and}} \cdots \mathbin{\mathrm{and}} a_j) + \gcd(a_i, a_{i+1}, a_{i+2}, \ldots, a_j)$, where gcd\gcd denotes the greatest common divisor.

Now, xtq wants to find a plan for using the brushes so that for each painting he needs to copy, his total score is as large as possible.

Input Format

The first line contains a positive integer TT, representing the number of paintings.

For each painting:

The first line contains two positive integers n,kn, k.

The second line contains nn positive integers a1,a2,a3,,ana_1, a_2, a_3, \ldots , a_n.

The third line contains kk integers b1,b2,b3,,bkb_1, b_2, b_3, \ldots , b_k.

Output Format

For each painting, output one integer, representing the maximum score xtq can obtain after completing this painting.

1
6 2
3 1 4 5 6 2
6 -2

31

Hint

Sample explanation:

xtq can start from 11 and gain an initial score of 66 points. The first segment is [1,2][1,2], gaining 55 points; the second segment is [3,4][3,4], gaining 1010 points; the third segment is [5,6][5,6], gaining 1010 points. In total, 3131 points.

Constraints:

For 20%20\% of the testdata, n10n\le 10.
For 40%40\% of the testdata, n3000n\le 3000.
For 70%70\% of the testdata, n30000n\le 30000.
For 100%100\% of the testdata, 1k<n3×1051\le k<n\le 3 \times {10}^5, T10T\le 10, 1ai2301\le a_i\le 2^{30}, 230bi230-2^{30}\le b_i\le 2^{30}.

The testdata has multiple levels, so it should not be too strict on constant factors.

Translated by ChatGPT 5