This is the hard version of the problem. The only difference is that in this version $$${1 \leq k \leq 5000}$$$ and sum of $$$n$$$ over all test cases does not exceed $$$5\times 10^6$$$.
An array is called colorful array if and only if all its numbers are distinct.
You are given three integers $$$n$$$, $$$m$$$, and $$$k$$$.
Your task is to construct an array $$$a$$$ of size $$$n$$$ satisfying:
The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.
Each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \leq n \leq 5000$$$, $$$0 \leq m \leq \frac{n(n+1)}{2}$$$, $$$\bf{1 \leq k \leq 5000}$$$).
NOTE: It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5\times 10^6$$$.
If such an array doesn't exist, output $$$-1$$$.
Otherwise, output $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ in a new line.
61 1 32 3 32 1 34 5 34 10 74 6 5
1 2 1 -1 2 1 1 1 4 5 6 7 1 4 4 5
In the fourth test case, $$$a=[2,1,1,1]$$$ has exactly $$$5$$$ colorful subarrays $$$[a_1]$$$, $$$[a_2]$$$, $$$[a_3]$$$, $$$[a_4]$$$, and $$$[a_1,a_2]$$$.