#P1811G2. Vlad and the Nice Paths (hard version)

    ID: 60 Type: RemoteJudge 3000ms 512MiB Tried: 0 Accepted: 0 Difficulty: 8 Uploaded By: Tags>binary searchcombinatoricsdata structuresdpmathtwo pointers*2200

Vlad and the Nice Paths (hard version)

Description

This is hard version of the problem, it differs from the easy one only by constraints on nn and kk.

Vlad found a row of nn tiles and the integer kk. The tiles are indexed from left to right and the ii-th tile has the color cic_i. After a little thought, he decided what to do with it.

You can start from any tile and jump to any number of tiles right, forming the path pp. Let's call the path pp of length mm nice if:

  • pp can be divided into blocks of length exactly kk, that is, mm is divisible by kk;
  • cp1=cp2==cpkc_{p_1} = c_{p_2} = \ldots = c_{p_k};
  • cpk+1=cpk+2==cp2kc_{p_{k+1}} = c_{p_{k+2}} = \ldots = c_{p_{2k}};
  • \ldots
  • cpmk+1=cpmk+2==cpmc_{p_{m-k+1}} = c_{p_{m-k+2}} = \ldots = c_{p_{m}};

Your task is to find the number of nice paths of maximum length. Since this number may be too large, print it modulo 109+710^9 + 7.

The first line of each test contains the integer tt (1t1041 \le t \le 10^4) — the number of test cases in the test.

The first line of each test case contains two integers nn and kk (1kn50001 \le k \le n \le 5000) — the number of tiles in a row and the length of the block.

The second line of each test case contains nn integers c1,c2,c3,,cnc_1, c_2, c_3, \dots, c_n (1cin1 \le c_i \le n) — tile colors.

It is guaranteed that the sum of n2n^2 over all test cases does not exceed 2510625 \cdot 10^6.

Print tt numbers, each of which is the answer to the corresponding test case — the number of nice paths of maximum length modulo 109+710^9 + 7.

Input

The first line of each test contains the integer tt (1t1041 \le t \le 10^4) — the number of test cases in the test.

The first line of each test case contains two integers nn and kk (1kn50001 \le k \le n \le 5000) — the number of tiles in a row and the length of the block.

The second line of each test case contains nn integers c1,c2,c3,,cnc_1, c_2, c_3, \dots, c_n (1cin1 \le c_i \le n) — tile colors.

It is guaranteed that the sum of n2n^2 over all test cases does not exceed 2510625 \cdot 10^6.

Output

Print tt numbers, each of which is the answer to the corresponding test case — the number of nice paths of maximum length modulo 109+710^9 + 7.

Sample Input 1

5
5 2
1 2 3 4 5
7 2
1 3 1 3 3 1 3
11 4
1 1 1 1 1 1 1 1 1 1 1
5 2
1 1 2 2 2
5 1
1 2 3 4 5

Sample Output 1

1
4
165
3
1

Note

In the first sample, it is impossible to make a nice path with a length greater than 00.

In the second sample, we are interested in the following paths:

  • 13451 \rightarrow 3 \rightarrow 4 \rightarrow 5
  • 24572 \rightarrow 4 \rightarrow 5 \rightarrow 7
  • 13571 \rightarrow 3 \rightarrow 5 \rightarrow 7
  • 13471 \rightarrow 3 \rightarrow 4 \rightarrow 7

In the third example, any path of length 88 is nice.