CF BUDDY
← Problems·

1811G2 · Vlad and the Nice Paths (hard version)

2200 · binary search, combinatorics, data structures

Problem: 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.

Input Format: 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 Format: 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.

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.

Sample Cases

Case 1

Input

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

Output

1
4
165
3
1

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback