This is the hard version of the problem. The only difference between the versions is the range of
.
Colin likes to play the Happy Eliminate game to kill time. Usually, the player is asked to find a fixed pattern in the given content, then eliminate it. The variety of patterns makes the game rich and exciting.
To research which pattern makes the game most exciting, Colin built a model: The contents given to the user are represented as a string

, and the pattern is another string

. In each turn of the game, the user can do one of the following two operations, and the game will be kept going until

becomes empty:
-
Delete the last character of the pattern
.
-
Find a substring of
that is equal to
, say
, then delete several characters in the prefix of
until
, i.e., (make
become
), and then delete the last character of the pattern
.
Colin defines a game's excitement as the maximum number of times the second operation can be performed. He wants to find the best pattern to maximize excitement, but he has no idea how to construct it. Thus, he turned it over to you, the top player of Happy Eliminate.
Recall that

represents the length of the string

, and
![s[i,j]](https://www.nowcoder.com/equation?tex=s%5Bi%2Cj%5D)
represents the substring of the string

, starting from the

-th character to the

-th character (including the

-th and the

-th).