Rescue Niwen! (Codeforces 1562E)
Tags: Greedy, string suffix structures

 Morning desert sun horizonRise above the sands of time...Fates Warning, "Exodus"After crossing the Windswept Wastes, Ori has finally reached the Windtorn Ruins to find the Heart of the Forest! However, the ancient repository containing this priceless Willow light did not want to open!Ori was taken aback, but the Voice of the Forest explained to him that the cunning Gorleks had decided to add protection to the repository.The Gorleks were very fond of the "string expansion" operation. They were also very fond of increasing subsequences.Suppose a string $$$s_1s_2s_3 \ldots s_n$$$ is given. Then its "expansion" is defined as the sequence of strings $$$s_1$$$, $$$s_1 s_2$$$, ..., $$$s_1 s_2 \ldots s_n$$$, $$$s_2$$$, $$$s_2 s_3$$$, ..., $$$s_2 s_3 \ldots s_n$$$, $$$s_3$$$, $$$s_3 s_4$$$, ..., $$$s_{n-1} s_n$$$, $$$s_n$$$. For example, the "expansion" the string 'abcd' will be the following sequence of strings: 'a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'. To open the ancient repository, Ori must find the size of the largest increasing subsequence of the "expansion" of the string $$$s$$$. Here, strings are compared lexicographically.Help Ori with this task!A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Input: Each test contains multiple test cases.The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows.The first line of each test case contains one positive integer $$$n$$$ ($$$1 \le n \le 5000$$$) — length of the string.The second line of each test case contains a non-empty string of length $$$n$$$, which consists of lowercase latin letters.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

Output: For every test case print one non-negative integer — the answer to the problem.

Note: In first test case the "expansion" of the string is: 'a', 'ac', 'acb', 'acba', 'acbac', 'c', 'cb', 'cba', 'cbac', 'b', 'ba', 'bac', 'a', 'ac', 'c'. The answer can be, for example, 'a', 'ac', 'acb', 'acba', 'acbac', 'b', 'ba', 'bac', 'c'.

Sample Inputs:
7
5
acbac
8
acabacba
12
aaaaaaaaaaaa
10
abacabadac
8
dcbaabcd
3
cba
6
sparky

Sample Outputs:
9
17
12
29
14
3
9

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def suffix_array(s):
    b = (len(s) - 1).bit_length()
    u = list(s)
    (l, j) = (len(u), 1)
    (v, w) = ([0] * l, [0] * l)
    for _ in range(b):
        m = max(u)
        s0 = [0] * (m + 3)
        for i in u:
            s0[i + 2] += 1
        for i in range(1, m + 3):
            s0[i] += s0[i - 1]
        for i in range(l):
            k = u[i] + 1
            v[s0[k]] = i - j
            s0[k] += 1
        for i in v:
            k = u[i]
            w[s0[k]] = i
            s0[k] += 1
        (c, la1, la2) = (0, 0, 0)
        for i in w:
            (x, y) = (u[i], u[(i + j) % l])
            if la1 ^ x or la2 ^ y:
                (la1, la2) = (x, y)
                c += 1
            v[i] = c
        (u, v) = (v, u)
        if c == l:
            break
        j <<= 1
    l = u[-1]
    sa = [0] * len(s)
    for i in range(len(s) - 1):
        sa[u[i] - l] = i
    sa[0] = len(sa) - 1
    return sa

def lcp_array(s, sa):
    l = len(s)
    (lcp, rank) = ([0] * l, [0] * l)
    for i in range(l):
        rank[sa[i]] = i
    v = 0
    for i in range(l):
        if not rank[i]:
            continue
        j = sa[rank[i] - 1]
        u = min(i, j)
        while u + v < l and s[i + v] == s[j + v]:
            v += 1
        lcp[rank[i]] = v
        v = max(v - 1, 0)
    return lcp
t = int(input())
ans = []
inf = pow(10, 9) + 1
for _ in range(t):
    n = int(input())
    s = list(input().rstrip())
    s = [i - 96 for i in s] + [0]
    sa = suffix_array(s)
    lcp = lcp_array(s, sa)[2:]
    sa = sa[1:]
    u = [0] * n
    for i in range(n):
        u[sa[i]] = i
    dp = [0] * n
    dp[0] = n
    for i in range(1, n):
        (v, dpi) = (u[i], n - i)
        mi = inf
        for j in range(v - 1, -1, -1):
            mi = min(mi, lcp[j])
            if sa[j] < i:
                dpi = max(dpi, dp[sa[j]] + n - i - mi)
        dp[i] = dpi
    ans0 = max(dp)
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys
input = sys.stdin.readline

def SA_IS(a):
    a += [0]
    k = max(a) + 1
    n = len(a)

    def induce_l(sa, a, n, k, stype):
        bucket = get_buckets(a, k, 1)
        for i in range(n):
            j = sa[i] - 1
            if j >= 0 and (not stype[j]):
                sa[bucket[a[j]]] = j
                bucket[a[j]] += 1

    def induce_s(sa, a, n, k, stype):
        bucket = get_buckets(a, k, 0)
        for i in range(n)[::-1]:
            j = sa[i] - 1
            if j >= 0 and stype[j]:
                bucket[a[j]] -= 1
                sa[bucket[a[j]]] = j

    def get_buckets(a, k, start=0):
        bucket = [0] * k
        for item in a:
            bucket[item] += 1
        s = 0
        for i in range(k):
            s += bucket[i]
            bucket[i] = s - (bucket[i] if start else 0)
        return bucket

    def set_lms(a, n, k, default_order):
        bucket = get_buckets(a, k)
        sa = [-1] * n
        for i in default_order[::-1]:
            bucket[a[i]] -= 1
            sa[bucket[a[i]]] = i
        return sa

    def induce(a, n, k, stype, default_order):
        sa = set_lms(a, n, k, default_order)
        induce_l(sa, a, n, k, stype)
        induce_s(sa, a, n, k, stype)
        return sa

    def rename_LMS_substring(sa, a, n, stype, LMS, l):
        sa = [_s for _s in sa if LMS[_s]]
        tmp = [-1] * (n // 2) + [0]
        dupl = 0
        for _ in range(1, l):
            (i, j) = (sa[_ - 1], sa[_])
            for ii in range(n):
                if a[i + ii] != a[j + ii] or stype[i + ii] != stype[j + ii]:
                    break
                if ii and (LMS[i + ii] or LMS[j + ii]):
                    dupl += 1
                    break
            tmp[j // 2] = _ - dupl
        tmp = [t for t in tmp if t >= 0]
        return (tmp, dupl)

    def calc(a, n, k):
        stype = [1] * n
        for i in range(n - 1)[::-1]:
            if a[i] > a[i + 1] or (a[i] == a[i + 1] and stype[i + 1] == 0):
                stype[i] = 0
        LMS = [1 if stype[i] and (not stype[i - 1]) else 0 for i in range(n - 1)] + [1]
        l = sum(LMS)
        lms = [i for i in range(n) if LMS[i]]
        sa = induce(a, n, k, stype, lms)
        (renamed_LMS, dupl) = rename_LMS_substring(sa, a, n, stype, LMS, l)
        if dupl:
            sub_sa = calc(renamed_LMS, l, l - dupl)
        else:
            sub_sa = [0] * l
            for i in range(l):
                sub_sa[renamed_LMS[i]] = i
        lms = [lms[sub_sa[i]] for i in range(l)]
        sa = induce(a, n, k, stype, lms)
        return sa
    sa = calc(a, n, k)
    return sa

def LCP(s, n, sa):
    lcp = [-1] * (n + 1)
    rank = [0] * (n + 1)
    for i in range(n + 1):
        rank[sa[i]] = i
    h = 0
    lcp[0] = 0
    for i in range(n):
        j = sa[rank[i] - 1]
        if h > 0:
            h -= 1
        while j + h < n and i + h < n and (s[j + h] == s[i + h]):
            h += 1
        lcp[rank[i] - 1] = h
    return lcp

def main():
    n = int(input())
    S = [ord(a) - 96 for a in input().strip()]
    SA = SA_IS(S)
    lcp = LCP(S, n, SA)
    dp = [0] * n
    for i in range(1, n + 1):
        pos = SA[i]
        plus = n - pos
        min_ = 10 ** 10
        for j in range(i - 1, 0, -1):
            p2 = SA[j]
            min_ = min(min_, lcp[j])
            if p2 < pos:
                dp[pos] = max(dp[pos], dp[p2] - min_)
        dp[pos] += plus
    print(max(dp))
for _ in range(int(input())):
    main()

Solution (Python):
import collections
import sys
input = sys.stdin.readline
for _ in range(int(input())):
    n = int(input())
    s = input()
    maxList = [n - index for index in range(n)]
    longestCommonPrefix = [0] * (n + 1)
    for index in range(n - 1, -1, -1):
        for j in range(index + 1, n):
            longestCommonPrefix[j] = longestCommonPrefix[j + 1] + 1 if s[index] == s[j] else 0
            if s[index + longestCommonPrefix[j]] < s[j + longestCommonPrefix[j]]:
                delta = maxList[j] - longestCommonPrefix[j] + n - index - maxList[index]
                if delta > 0:
                    maxList[index] += delta
    print(max(maxList))