-
Notifications
You must be signed in to change notification settings - Fork 6
/
suffixsorting.py
33 lines (31 loc) · 1.03 KB
/
suffixsorting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys
def suffix_array_construction(s):
n = len(s)
sa = list(range(n))
ra = [ord(s[i]) for i in range(n)]
k, maxi = 1, max(300, n)
while k < n:
for kk in [k, 0]: # count sort on k and 0 respectively
c = [0]*maxi
for i in range(n): c[ra[i+kk] if i+kk<n else 0] += 1
ss, temp = 0, [0]*n
for i in range(maxi): t = c[i]; c[i] = ss; ss += t
for i in range(n):
idx = ra[sa[i]+kk] if sa[i]+kk < n else 0
temp[c[idx]] = sa[i]
c[idx] += 1
sa = temp
temp, r = [0]*n, 0
temp[sa[0]] = r
for i in range(1, n):
r += ra[sa[i]] != ra[sa[i-1]] or ra[sa[i]+k] != ra[sa[i-1]+k]
temp[sa[i]] = r
ra = temp
if ra[sa[n-1]] == n-1: break
k *= 2
return sa
t = 0
for s in sys.stdin:
t = 1-t
if t: sa = suffix_array_construction(s.strip()+'\0')
else: print(*[sa[i+1] for i in map(int, s.split()[1:])])