Problem:
Score : 100 points

Problem Statement

You are given a string of length N. Calculate the number of distinct substrings of S.

Constraints

1 \leq N \leq 500,000

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

abcbcba

Sample Output 1

21

Sample Input 2

mississippi

Sample Output 2

53

Sample Input 3

ababacaca

Sample Output 3

33

Sample Input 4

aaaaa

Sample Output 4

5

Solution in PyPy3 (7.3.0) (judge verdict: Wrong Answer)

import sys
input = sys.stdin.readline
S = input()[: -1]
N = len(S)

def SuffixArray(n, s):
  s += "??"
  s0 = []
  s1 = []
  s2 = []
  for i in range(n):
    if i % 3 == 1: s1.append((s[i: i + 3], i))
    if i % 3 == 2: s2.append((s[i: i + 3], i))
  s12 = s1 + s2
  s12.sort(key = lambda x: (x[0], -x[1]))
  table = [-1] * (n + 2)
  for i in range(len(s12)): table[s12[i][1]] = i
  for i in range(n):
    if i % 3 == 0: s0.append((s[i], table[i + 1], i))
  s0.sort(key = lambda x: (x[0], x[1]))
  sa = []
  s0.reverse()
  s12.reverse()
  while len(sa) < n:
    if len(s0) == 0:
      sa.append(s12.pop()[1])
      continue
    if len(s12) == 0:
      sa.append(s0.pop()[2])
      continue
    c, r, i = s0.pop()
    x, j = s12.pop()
    cc = s[i + 1]
    rr = table[i + 2]
    xx = s[j + 1]
    xr = table[j + 1]
    xrr = table[j + 2]
    if j % 3 == 1:
      if c < x[0]:
        sa.append(i)
        s12.append((x, j))
      if c > x[0]:
        sa.append(j)
        s0.append((c, r, i))
      if c == x[0]:
        if r < xr:
          sa.append(i)
          s12.append((x, j))
        if r > xr:
          sa.append(j)
          s0.append((c, r, i))
    if j % 3 == 2:
      if c < x[0]:
        sa.append(i)
        s12.append((x, j))
      if c > x[0]:
        sa.append(j)
        s0.append((c, r, i))
      if c == x[0]:
        if cc < xx:
          sa.append(i)
          s12.append((x, j))
        if cc > xx:
          sa.append(j)
          s0.append((c, r, i))
        if cc == xx:
          if rr < xrr:
            sa.append(i)
            s12.append((x, j))
          if rr > xrr:
            sa.append(j)
            s0.append((c, r, i))
  return sa

def LCPArray(n, s, sa):
  r = [0] * n
  for i in range(n): r[sa[i]] = i
  lcp = [0] * (n - 1)
  x = 0
  for i in range(n):
    if x > 0: x -= 1
    if r[i] == 0: continue
    j = sa[r[i] - 1]
    while max(i, j) + x < n:
      if s[i + x] != s[j + x]: break
      x += 1
    lcp[r[i] - 1] = x
  return lcp 
sa = SuffixArray(N, S)
lcp = LCPArray(N, S, sa)
print(N * (N + 1) // 2 - sum(lcp))