-
Notifications
You must be signed in to change notification settings - Fork 30
/
广义后缀自动机.go
1669 lines (1506 loc) · 44.6 KB
/
广义后缀自动机.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 广义后缀自动机(General Suffix Automaton,GSA)
// https://www.yhzq-blog.cc/%e5%b9%bf%e4%b9%89%e5%90%8e%e7%bc%80%e8%87%aa%e5%8a%a8%e6%9c%ba%e6%80%bb%e7%bb%93/
// https://zhuanlan.zhihu.com/p/34838533
// https://oi-wiki.org/string/general-sam/
// https://www.luogu.com.cn/article/pm10t1pc
// https://www.luogu.com/article/w967d5rp
//
// note:
//
// 0. 一个能接受多个串所有子串的自动机。
// 1. 构建方式:
// - 伪广义后缀自动机:
// !如果给出的是多个字符串而不是一个trie,则可以使用.
// 对每个串,重复在同一个 SAM 上进行建立.
// !每次建完一个串以后就把lastPos 指针移到root上面,接着建下一个串。
// 注意"插入字符串时需要看一下当前准备插入的位置是否已经有结点了".
// 如果有的话我们只需要在其基础上额外判断一下拆分 SAM 结点的情况;否则的话就和普通的 SAM 插入一模一样了
// - Trie树上的广义后缀自动机:建立在 Trie 树上的 SAM 称为广义 SAM
//
// !2. 自动机和广义后缀自动机中"用于构建"该自动机的所有串的所有前缀节点的树链的并的长度和是 O(L*sqrt(L)) 的。
//
// !对文本串t[i]的每个前缀,在后缀链接树上向上跳标记每个endPos,表示该endPos包含了t[i]的子串.标记次数之和不超过O(Lsqrt(L)).
// 记count[u]为结点u的子树中的endPos的原串个数,则sum(count)的数量级为O(Lsqrt(L)),L为所有串长之和.
// 证明(利用根号分治):
// 则若一个串长S>SQRT(L),这样的串显然不超SQRT(L)个,而由于广义 SAM 上的节点数量级线性所以这里的总贡献数量级为O(LSQRT(L))。
// 而对于串长不超过SQRT(L)的串,贡献数量级为O(nSQRT(L))。
// https://blog.csdn.net/ylsoi/article/details/94476894
// https://ddosvoid.github.io/2020/10/18/%E6%B5%85%E8%B0%88%E6%A0%B9%E5%8F%B7%E7%AE%97%E6%B3%95/
// 喵星球上的点名 https://www.luogu.com.cn/problem/P2336
// Sevenk Love Oimaster https://www.luogu.com.cn/problem/SP8093
// !可以被线段树合并优化成O(nlogn).
//
// !3. 广义 SAM 出现子串查询:
// 对于 n 个串的广义后缀自动机,求出每个点对应的字符串是哪些原串的子串。
// 和线段树合并维护 Endpos 集合基本一致,将"每个串的每个前缀"对应的点附上对应串的标记,
// 然后在树结构上 DFS 进行线段树合并(pushUp到后缀)即可得到每个子串的出现位置。
package main
import (
"bufio"
"fmt"
"math/bits"
"os"
)
const SIGMA int32 = 26 // 字符集大小
const OFFSET int32 = 'a' // 字符集的起始字符
type Node struct {
Next [SIGMA]int32 // SAM 转移边
Link int32 // 后缀链接
MaxLen int32 // 当前节点对应的最长子串的长度
}
type SuffixAutomatonGeneral struct {
Nodes []*Node
n int32 // 当前字符串长度
doubling *DoublingSimple
}
func NewSuffixAutomatonGeneral() *SuffixAutomatonGeneral {
res := &SuffixAutomatonGeneral{}
res.Nodes = append(res.Nodes, res.newNode(-1, 0))
return res
}
// !需要在插入新串之前将lastPos置为0.
// eg:
//
// sam := NewSuffixAutomatonGeneral()
// for _,word := range words {
// lastPos = 0
// for _,c := range word {
// lastPos = sam.Add(lastPos,c)
// }
// }
//
// 返回当前前缀对应的节点编号(lastPos).
func (sam *SuffixAutomatonGeneral) Add(lastPos int32, char int32) int32 {
c := char - OFFSET
sam.n++
// 判断当前转移结点是否存在.
if tmp := sam.Nodes[lastPos].Next[c]; tmp != -1 {
lastNode, nextNode := sam.Nodes[lastPos], sam.Nodes[tmp]
if lastNode.MaxLen+1 == nextNode.MaxLen {
return tmp
} else {
newQ := int32(len(sam.Nodes))
sam.Nodes = append(sam.Nodes, sam.newNode(nextNode.Link, lastNode.MaxLen+1))
sam.Nodes[newQ].Next = nextNode.Next
sam.Nodes[tmp].Link = newQ
for lastPos != -1 && sam.Nodes[lastPos].Next[c] == tmp {
sam.Nodes[lastPos].Next[c] = newQ
lastPos = sam.Nodes[lastPos].Link
}
return newQ
}
}
newNode := int32(len(sam.Nodes))
// 新增一个实点以表示当前最长串
sam.Nodes = append(sam.Nodes, sam.newNode(-1, sam.Nodes[lastPos].MaxLen+1))
p := lastPos
for p != -1 && sam.Nodes[p].Next[c] == -1 {
sam.Nodes[p].Next[c] = newNode
p = sam.Nodes[p].Link
}
q := int32(0)
if p != -1 {
q = sam.Nodes[p].Next[c]
}
if p == -1 || sam.Nodes[p].MaxLen+1 == sam.Nodes[q].MaxLen {
sam.Nodes[newNode].Link = q
} else {
// 不够用,需要新增一个虚点
newQ := int32(len(sam.Nodes))
sam.Nodes = append(sam.Nodes, sam.newNode(sam.Nodes[q].Link, sam.Nodes[p].MaxLen+1))
sam.Nodes[len(sam.Nodes)-1].Next = sam.Nodes[q].Next
sam.Nodes[q].Link = newQ
sam.Nodes[newNode].Link = newQ
for p != -1 && sam.Nodes[p].Next[c] == q {
sam.Nodes[p].Next[c] = newQ
p = sam.Nodes[p].Link
}
}
return newNode
}
func (sam *SuffixAutomatonGeneral) AddString(s string, prefixEndFn func(i, pos int32)) (lastPos int32) {
lastPos = 0
for i, c := range s {
lastPos = sam.Add(lastPos, c)
if prefixEndFn != nil {
prefixEndFn(int32(i), lastPos)
}
}
return
}
func (sam *SuffixAutomatonGeneral) Size() int32 {
return int32(len(sam.Nodes))
}
// 后缀链接树.也叫 parent tree.
func (sam *SuffixAutomatonGeneral) BuildTree() [][]int32 {
n := int32(len(sam.Nodes))
graph := make([][]int32, n)
for v := int32(1); v < n; v++ {
p := sam.Nodes[v].Link
graph[p] = append(graph[p], v)
}
return graph
}
func (sam *SuffixAutomatonGeneral) BuildDAG() [][]int32 {
n := int32(len(sam.Nodes))
graph := make([][]int32, n)
for v := int32(0); v < n; v++ {
for _, to := range sam.Nodes[v].Next {
if to != -1 {
graph[v] = append(graph[v], to)
}
}
}
return graph
}
// 将结点按照长度进行计数排序,返回后缀链接树的dfs顺序.
// 注意:后缀链接树上父亲的MaxLen值一定小于儿子,但不能认为编号小的节点MaxLen值也小.
// 常数比建图 + dfs 小.
func (sam *SuffixAutomatonGeneral) GetDfsOrder() []int32 {
nodes, size, n := sam.Nodes, sam.Size(), sam.n
counter := make([]int32, n+1)
for i := int32(0); i < size; i++ {
counter[nodes[i].MaxLen]++
}
for i := int32(1); i <= n; i++ {
counter[i] += counter[i-1]
}
order := make([]int32, size)
for i := size - 1; i >= 0; i-- {
v := nodes[i].MaxLen
counter[v]--
order[counter[v]] = i
}
return order
}
// 对每个模式串,返回其在sam上各个endPos的大小.
// dfsOrder: 后缀链接树的dfs顺序.
// isPrefix: 判断pos是否是模式串的前缀.
func (sam *SuffixAutomatonGeneral) GetEndPosSize(dfsOrder []int32, isPrefix func(pos int32) bool) []int32 {
size := sam.Size()
endPosSize := make([]int32, size)
for i := size - 1; i >= 1; i-- {
cur := dfsOrder[i]
if isPrefix(cur) { // 实点
endPosSize[cur]++
}
pre := sam.Nodes[cur].Link
endPosSize[pre] += endPosSize[cur]
}
return endPosSize
}
// 给定子串的起始位置和结束位置,返回子串在fail树上的位置.
// 快速定位子串, 可以与其它字符串算法配合使用.
// 倍增往上跳到 MaxLen>=end-start 的最后一个节点.
// start: 子串起始位置, end: 子串结束位置, endPosOfEnd: 子串结束位置在fail树上的位置.
func (sam *SuffixAutomatonGeneral) LocateSubstring(start, end int32, endPosOfEnd int32) (pos int32) {
target := end - start
_, pos = sam.Doubling().MaxStep(endPosOfEnd, func(p int32) bool { return sam.Nodes[p].MaxLen >= target })
return
}
func (sam *SuffixAutomatonGeneral) DistinctSubstringAt(pos int32) int32 {
if pos == 0 {
return 0
}
return sam.Nodes[pos].MaxLen - sam.Nodes[sam.Nodes[pos].Link].MaxLen
}
// 本质不同的子串个数.
func (sam *SuffixAutomatonGeneral) DistinctSubstring() int {
res := 0
for i := 1; i < len(sam.Nodes); i++ {
res += int(sam.DistinctSubstringAt(int32(i)))
}
return res
}
// 获取pattern在sam上的位置.
func (sam *SuffixAutomatonGeneral) GetPos(pattern string) (pos int32, ok bool) {
pos = 0
for _, c := range pattern {
pos = sam.Nodes[pos].Next[c-OFFSET]
if pos == -1 {
return -1, false
}
}
return pos, true
}
// 后缀连接树上倍增.
func (sam *SuffixAutomatonGeneral) Doubling() *DoublingSimple {
if sam.doubling == nil {
size := sam.Size()
doubling := NewDoubling(size, int(size))
for i := int32(1); i < size; i++ {
doubling.Add(i, sam.Nodes[i].Link)
}
doubling.Build()
sam.doubling = doubling
}
return sam.doubling
}
func (sam *SuffixAutomatonGeneral) newNode(link, maxLen int32) *Node {
res := &Node{Link: link, MaxLen: maxLen}
for i := int32(0); i < SIGMA; i++ {
res.Next[i] = -1
}
return res
}
type E = int
func e() E { return 0 }
func op(a, b E) E {
return a + b
}
func merge(a, b E) E { // 合并两个不同的树的结点的函数
// return min32(1, a+b)
return a + b
}
type SegNode struct {
value E
leftChild, rightChild *SegNode
}
func (n *SegNode) String() string {
return fmt.Sprintf("%v", n.value)
}
type SegmentTreeMerger struct {
left, right int32
}
// 指定闭区间[left,right]建立Merger.
func NewSegmentTreeMerger(left, right int32) *SegmentTreeMerger {
return &SegmentTreeMerger{left: left, right: right}
}
// NewRoot().
func (sm *SegmentTreeMerger) Alloc() *SegNode {
return &SegNode{value: e()}
}
// 权值线段树求第 k 小.
// 调用前需保证 1 <= k <= node.value.
func (sm *SegmentTreeMerger) Kth(node *SegNode, k int32, getCount func(node *SegNode) int32) (res int32, ok bool) {
if k < 1 || k > getCount(node) {
return
}
return sm._kth(k, node, sm.left, sm.right, getCount), true
}
func (sm *SegmentTreeMerger) Get(node *SegNode, index int32) E {
return sm._get(node, index, sm.left, sm.right)
}
func (sm *SegmentTreeMerger) Set(node *SegNode, index int32, value E) {
sm._set(node, index, value, sm.left, sm.right)
}
func (sm *SegmentTreeMerger) Query(node *SegNode, left, right int32) E {
return sm._query(node, left, right, sm.left, sm.right)
}
func (sm *SegmentTreeMerger) QueryAll(node *SegNode) E {
return sm._eval(node)
}
func (sm *SegmentTreeMerger) Update(node *SegNode, index int32, value E) {
sm._update(node, index, value, sm.left, sm.right)
}
// 用一个新的节点存合并的结果,会生成重合节点数量的新节点.
func (sm *SegmentTreeMerger) Merge(a, b *SegNode) *SegNode {
return sm._merge(a, b, sm.left, sm.right)
}
// 把第二棵树直接合并到第一棵树上,比较省空间,缺点是会丢失合并前树的信息.
func (sm *SegmentTreeMerger) MergeDestructively(a, b *SegNode) *SegNode {
return sm._mergeDestructively(a, b, sm.left, sm.right)
}
// 线段树分裂,将区间 [left,right] 从原树分离到 other 上, this 为原树的剩余部分.
func (sm *SegmentTreeMerger) Split(node *SegNode, left, right int32) (this, other *SegNode) {
this, other = sm._split(node, nil, left, right, sm.left, sm.right)
return
}
func (sm *SegmentTreeMerger) _kth(k int32, node *SegNode, left, right int32, getCount func(*SegNode) int32) int32 {
if left == right {
return left
}
mid := (left + right) >> 1
leftCount := int32(0)
if node.leftChild != nil {
leftCount = getCount(node.leftChild)
}
if leftCount >= k {
return sm._kth(k, node.leftChild, left, mid, getCount)
} else {
return sm._kth(k-leftCount, node.rightChild, mid+1, right, getCount)
}
}
func (sm *SegmentTreeMerger) _get(node *SegNode, index int32, left, right int32) E {
if node == nil {
return e()
}
if left == right {
return node.value
}
mid := (left + right) >> 1
if index <= mid {
return sm._get(node.leftChild, index, left, mid)
} else {
return sm._get(node.rightChild, index, mid+1, right)
}
}
func (sm *SegmentTreeMerger) _query(node *SegNode, L, R int32, left, right int32) E {
if node == nil {
return e()
}
if L <= left && right <= R {
return node.value
}
mid := (left + right) >> 1
if R <= mid {
return sm._query(node.leftChild, L, R, left, mid)
}
if L > mid {
return sm._query(node.rightChild, L, R, mid+1, right)
}
return op(sm._query(node.leftChild, L, R, left, mid), sm._query(node.rightChild, L, R, mid+1, right))
}
func (sm *SegmentTreeMerger) _set(node *SegNode, index int32, value E, left, right int32) {
if left == right {
node.value = value
return
}
mid := (left + right) >> 1
if index <= mid {
if node.leftChild == nil {
node.leftChild = sm.Alloc()
}
sm._set(node.leftChild, index, value, left, mid)
} else {
if node.rightChild == nil {
node.rightChild = sm.Alloc()
}
sm._set(node.rightChild, index, value, mid+1, right)
}
node.value = op(sm._eval(node.leftChild), sm._eval(node.rightChild))
}
func (sm *SegmentTreeMerger) _update(node *SegNode, index int32, value E, left, right int32) {
if left == right {
node.value = op(node.value, value)
return
}
mid := (left + right) >> 1
if index <= mid {
if node.leftChild == nil {
node.leftChild = sm.Alloc()
}
sm._update(node.leftChild, index, value, left, mid)
} else {
if node.rightChild == nil {
node.rightChild = sm.Alloc()
}
sm._update(node.rightChild, index, value, mid+1, right)
}
node.value = op(sm._eval(node.leftChild), sm._eval(node.rightChild))
}
func (sm *SegmentTreeMerger) _merge(a, b *SegNode, left, right int32) *SegNode {
if a == nil || b == nil {
if a == nil {
return b
}
return a
}
newNode := sm.Alloc()
if left == right {
newNode.value = merge(a.value, b.value)
return newNode
}
mid := (left + right) >> 1
newNode.leftChild = sm._merge(a.leftChild, b.leftChild, left, mid)
newNode.rightChild = sm._merge(a.rightChild, b.rightChild, mid+1, right)
newNode.value = op(sm._eval(newNode.leftChild), sm._eval(newNode.rightChild))
return newNode
}
func (sm *SegmentTreeMerger) _mergeDestructively(a, b *SegNode, left, right int32) *SegNode {
if a == nil || b == nil {
if a == nil {
return b
}
return a
}
if left == right {
a.value = merge(a.value, b.value)
return a
}
mid := (left + right) >> 1
a.leftChild = sm._mergeDestructively(a.leftChild, b.leftChild, left, mid)
a.rightChild = sm._mergeDestructively(a.rightChild, b.rightChild, mid+1, right)
a.value = op(sm._eval(a.leftChild), sm._eval(a.rightChild))
return a
}
func (sm *SegmentTreeMerger) _split(a, b *SegNode, L, R int32, left, right int32) (*SegNode, *SegNode) {
if a == nil || L > right || R < left {
return a, nil
}
if L <= left && right <= R {
return nil, a
}
if b == nil {
b = sm.Alloc()
}
mid := (left + right) >> 1
a.leftChild, b.leftChild = sm._split(a.leftChild, b.leftChild, L, R, left, mid)
a.rightChild, b.rightChild = sm._split(a.rightChild, b.rightChild, L, R, mid+1, right)
a.value = op(sm._eval(a.leftChild), sm._eval(a.rightChild))
b.value = op(sm._eval(b.leftChild), sm._eval(b.rightChild))
return a, b
}
func (sm *SegmentTreeMerger) _eval(node *SegNode) E {
if node == nil {
return e()
}
return node.value
}
// !注意不存在的情况(maxCount=0).
type MaxCount = int32
type SegNode2 struct {
MaxCount MaxCount // 出现次数最多的权值出现的次数.
MaxIndex int32 // 出现次数最多的权值.如果有多个,取最小的.
leftChild, rightChild *SegNode2
}
func (n *SegNode2) String() string {
return fmt.Sprintf("%v", n.MaxCount)
}
type SegmentTreeOnRangeWithIndex struct {
min, max int32
}
// 指定闭区间[min,max]建立权值线段树.
func NewSegmentTreeOnRangeWithIndex(min, max int32) *SegmentTreeOnRangeWithIndex {
return &SegmentTreeOnRangeWithIndex{min: min, max: max}
}
// NewRoot().
func (sm *SegmentTreeOnRangeWithIndex) Alloc() *SegNode2 {
return &SegNode2{}
}
func (sm *SegmentTreeOnRangeWithIndex) Get(node *SegNode2, index int32) MaxCount {
return sm._get(node, index, sm.min, sm.max)
}
func (sm *SegmentTreeOnRangeWithIndex) Set(node *SegNode2, index int32, count MaxCount) {
sm._set(node, index, count, sm.min, sm.max)
}
func (sm *SegmentTreeOnRangeWithIndex) Query(node *SegNode2, left, right int32) (maxCount MaxCount, maxIndex int32) {
return sm._query(node, left, right, sm.min, sm.max)
}
func (sm *SegmentTreeOnRangeWithIndex) QueryAll(node *SegNode2) (maxCount MaxCount, maxIndex int32) {
if node == nil {
return
}
return node.MaxCount, node.MaxIndex
}
func (sm *SegmentTreeOnRangeWithIndex) Add(node *SegNode2, index int32, count MaxCount) {
sm._update(node, index, count, sm.min, sm.max)
}
// 用一个新的节点存合并的结果,会生成重合节点数量的新节点.
func (sm *SegmentTreeOnRangeWithIndex) Merge(a, b *SegNode2) *SegNode2 {
return sm._merge(a, b, sm.min, sm.max)
}
// 把第二棵树直接合并到第一棵树上,比较省空间,缺点是会丢失合并前树的信息.
func (sm *SegmentTreeOnRangeWithIndex) MergeDestructively(a, b *SegNode2) *SegNode2 {
return sm._mergeDestructively(a, b, sm.min, sm.max)
}
// 线段树分裂,将区间 [left,right] 从原树分离到 other 上, this 为原树的剩余部分.
func (sm *SegmentTreeOnRangeWithIndex) Split(node *SegNode2, left, right int32) (this, other *SegNode2) {
this, other = sm._split(node, nil, left, right, sm.min, sm.max)
return
}
func (sm *SegmentTreeOnRangeWithIndex) _get(node *SegNode2, index int32, left, right int32) MaxCount {
if node == nil {
return 0
}
if left == right {
return node.MaxCount
}
mid := (left + right) >> 1
if index <= mid {
return sm._get(node.leftChild, index, left, mid)
} else {
return sm._get(node.rightChild, index, mid+1, right)
}
}
func (sm *SegmentTreeOnRangeWithIndex) _query(node *SegNode2, L, R int32, left, right int32) (maxCount MaxCount, maxIndex int32) {
if node == nil {
return
}
if L <= left && right <= R {
return node.MaxCount, node.MaxIndex
}
mid := (left + right) >> 1
if R <= mid {
return sm._query(node.leftChild, L, R, left, mid)
}
if L > mid {
return sm._query(node.rightChild, L, R, mid+1, right)
}
c1, i1 := sm._query(node.leftChild, L, R, left, mid)
c2, i2 := sm._query(node.rightChild, L, R, mid+1, right)
if c1 > c2 {
return c1, i1
} else if c1 < c2 {
return c2, i2
}
if i1 <= i2 {
return c1, i1
} else {
return c2, i2
}
}
func (sm *SegmentTreeOnRangeWithIndex) _set(node *SegNode2, index int32, count MaxCount, left, right int32) {
if left == right {
node.MaxCount = count
node.MaxIndex = left
return
}
mid := (left + right) >> 1
if index <= mid {
if node.leftChild == nil {
node.leftChild = sm.Alloc()
}
sm._set(node.leftChild, index, count, left, mid)
} else {
if node.rightChild == nil {
node.rightChild = sm.Alloc()
}
sm._set(node.rightChild, index, count, mid+1, right)
}
sm._pushUp(node)
}
func (sm *SegmentTreeOnRangeWithIndex) _update(node *SegNode2, index int32, count MaxCount, left, right int32) {
if left == right {
node.MaxCount += count
node.MaxIndex = left
return
}
mid := (left + right) >> 1
if index <= mid {
if node.leftChild == nil {
node.leftChild = sm.Alloc()
}
sm._update(node.leftChild, index, count, left, mid)
} else {
if node.rightChild == nil {
node.rightChild = sm.Alloc()
}
sm._update(node.rightChild, index, count, mid+1, right)
}
sm._pushUp(node)
}
func (sm *SegmentTreeOnRangeWithIndex) _merge(a, b *SegNode2, left, right int32) *SegNode2 {
if a == nil || b == nil {
if a == nil {
return b
}
return a
}
newNode := sm.Alloc()
if left == right {
newNode.MaxCount = a.MaxCount + b.MaxCount
newNode.MaxIndex = left
return newNode
}
mid := (left + right) >> 1
newNode.leftChild = sm._merge(a.leftChild, b.leftChild, left, mid)
newNode.rightChild = sm._merge(a.rightChild, b.rightChild, mid+1, right)
sm._pushUp(newNode)
return newNode
}
func (sm *SegmentTreeOnRangeWithIndex) _mergeDestructively(a, b *SegNode2, left, right int32) *SegNode2 {
if a == nil || b == nil {
if a == nil {
return b
}
return a
}
if left == right {
a.MaxCount += b.MaxCount
a.MaxIndex = left
return a
}
mid := (left + right) >> 1
a.leftChild = sm._mergeDestructively(a.leftChild, b.leftChild, left, mid)
a.rightChild = sm._mergeDestructively(a.rightChild, b.rightChild, mid+1, right)
sm._pushUp(a)
return a
}
func (sm *SegmentTreeOnRangeWithIndex) _split(a, b *SegNode2, L, R int32, left, right int32) (*SegNode2, *SegNode2) {
if a == nil || L > right || R < left {
return a, nil
}
if L <= left && right <= R {
return nil, a
}
if b == nil {
b = sm.Alloc()
}
mid := (left + right) >> 1
a.leftChild, b.leftChild = sm._split(a.leftChild, b.leftChild, L, R, left, mid)
a.rightChild, b.rightChild = sm._split(a.rightChild, b.rightChild, L, R, mid+1, right)
sm._pushUp(a)
sm._pushUp(b)
return a, b
}
func (sm *SegmentTreeOnRangeWithIndex) _evelCount(node *SegNode2) MaxCount {
if node == nil {
return 0
}
return node.MaxCount
}
func (sm *SegmentTreeOnRangeWithIndex) _pushUp(node *SegNode2) {
left, right := node.leftChild, node.rightChild
b1, b2 := left == nil, right == nil
if b1 || b2 {
if b1 && b2 {
return
}
if b1 {
node.MaxCount = right.MaxCount
node.MaxIndex = right.MaxIndex
} else {
node.MaxCount = left.MaxCount
node.MaxIndex = left.MaxIndex
}
} else {
if left.MaxCount > right.MaxCount {
node.MaxCount = left.MaxCount
node.MaxIndex = left.MaxIndex
} else if left.MaxCount < right.MaxCount {
node.MaxCount = right.MaxCount
node.MaxIndex = right.MaxIndex
} else {
if left.MaxIndex <= right.MaxIndex {
node.MaxCount = left.MaxCount
node.MaxIndex = left.MaxIndex
} else {
node.MaxCount = right.MaxCount
node.MaxIndex = right.MaxIndex
}
}
}
}
type DoublingSimple struct {
n int32
log int32
to []int32
}
func NewDoubling(n int32, maxStep int) *DoublingSimple {
res := &DoublingSimple{n: n, log: int32(bits.Len(uint(maxStep)))}
size := n * res.log
res.to = make([]int32, size)
for i := int32(0); i < size; i++ {
res.to[i] = -1
}
return res
}
func (d *DoublingSimple) Add(from, to int32) {
d.to[from] = to
}
func (d *DoublingSimple) Build() {
n := d.n
for k := int32(0); k < d.log-1; k++ {
for v := int32(0); v < n; v++ {
w := d.to[k*n+v]
next := (k+1)*n + v
if w == -1 {
d.to[next] = -1
continue
}
d.to[next] = d.to[k*n+w]
}
}
}
// 求从 `from` 状态开始转移 `step` 次的最终状态的编号。
// 不存在时返回 -1。
func (d *DoublingSimple) Jump(from int32, step int) (to int32) {
to = from
for k := int32(0); k < d.log; k++ {
if to == -1 {
return
}
if step&(1<<k) != 0 {
to = d.to[k*d.n+to]
}
}
return
}
// 求从 `from` 状态开始转移 `step` 次,满足 `check` 为 `true` 的最大的 `step` 以及最终状态的编号。
func (d *DoublingSimple) MaxStep(from int32, check func(next int32) bool) (step int, to int32) {
for k := d.log - 1; k >= 0; k-- {
tmp := d.to[k*d.n+from]
if tmp == -1 {
continue
}
if check(tmp) {
step |= 1 << k
from = tmp
}
}
to = from
return
}
type Bitset []uint
func NewBitset(n int32) Bitset { return make(Bitset, n>>6+1) }
func (b Bitset) Set(p int32) { b[p>>6] |= 1 << (p & 63) }
func (b Bitset) Has(p int32) bool { return b[p>>6]&(1<<(p&63)) != 0 }
func (b Bitset) Reset(p int32) { b[p>>6] &^= 1 << (p & 63) }
func (b Bitset) Flip(p int32) { b[p>>6] ^= 1 << (p & 63) }
func abs32(a int32) int32 {
if a < 0 {
return -a
}
return a
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func min32(a, b int32) int32 {
if a < b {
return a
}
return b
}
func max32(a, b int32) int32 {
if a > b {
return a
}
return b
}
func main() {
// P3181()
// P4081()
// P6139()
// bzoj3926()
// SP8093()
// CF204E()
// CF204E线段树合并()
// CF316G3()
// CF427D()
// CF452E()
// CF547E()
CF616F()
// CF666E()
}
// P3181 [HAOI2016] 找相同字符 (分别维护不同串的 size)
// https://www.luogu.com.cn/problem/P3181
// !求两个字符串的相同子串数量。
//
// 输入SAM,求出每个串对应的endPosSize后,按照dfs序逆序dp.
// 每个endPos的贡献为size1*size2*count.
func P3181() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
var s, t string
fmt.Fscan(in, &s, &t)
sam := NewSuffixAutomatonGeneral()
maxSize := int32(2 * (len(s) + len(t)))
isPrefix1 := NewBitset(maxSize)
sam.AddString(s, func(_, pos int32) { isPrefix1.Set(pos) })
isPrefix2 := NewBitset(maxSize)
sam.AddString(t, func(_, pos int32) { isPrefix2.Set(pos) })
size := sam.Size()
dfsOrder := sam.GetDfsOrder()
endPosSize1 := sam.GetEndPosSize(dfsOrder, isPrefix1.Has)
endPosSize2 := sam.GetEndPosSize(dfsOrder, isPrefix2.Has)
res := 0
for i := size - 1; i >= 1; i-- {
node := sam.Nodes[i]
count := int(node.MaxLen - sam.Nodes[node.Link].MaxLen)
size1, size2 := int(endPosSize1[i]), int(endPosSize2[i])
res += size1 * size2 * count
}
fmt.Fprintln(out, res)
}
// P4081 [USACO17DEC] Standing Out from the Herd P
// https://www.luogu.com.cn/problem/P4081
//
// 给定n个模式串.对每个模式串,求出本质不同的子串个数,且子串不在其他模式串中出现.
// 每个串在自动机上跑一下,然后把经过的点以及他们的parent树上的祖先全部标记上当前串的编号.
// 如果一个点被标记了两次,那么这个点所代表的子串必然不是本质相同的,就不能算
func P4081() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
var n int32
fmt.Fscan(in, &n)
words := make([]string, n)
for i := int32(0); i < n; i++ {
fmt.Fscan(in, &words[i])
}
sam := NewSuffixAutomatonGeneral()
for _, v := range words {
sam.AddString(v, nil)
}
size := sam.Size()
nodes := sam.Nodes
belong := make([][]int32, size)
visitedTime := make([]int32, size)
for i := int32(0); i < size; i++ {
visitedTime[i] = -1
}
// 对文本串t[i]的每个前缀,在后缀链接树上向上跳标记每个endPos,表示该endPos包含了t[i]的子串.
// 标记次数之和不超过O(Lsqrt(L)).
markChain := func(sid int32, pos int32) {
for pos >= 0 && visitedTime[pos] != sid {
visitedTime[pos] = sid
if len(belong[pos]) >= 2 {
break
}
belong[pos] = append(belong[pos], sid)
pos = nodes[pos].Link
}
}
// 标记所有文本串的子串.
for i, w := range words {
pos := int32(0)
for _, c := range w {
pos = nodes[pos].Next[c-OFFSET]
markChain(int32(i), pos)
}
}
res := make([]int32, n)
for i := int32(1); i < size; i++ {
if len(belong[i]) == 1 {
res[belong[i][0]] += sam.DistinctSubstringAt(i)
}
}
for _, v := range res {
fmt.Fprintln(out, v)
}
}
// P6139 【模板】广义后缀自动机(广义 SAM)
// https://www.luogu.com.cn/problem/P6139
// 求多个字符串的本质不同子串个数.
// 同时需要输出广义后缀自动机的点数.
func P6139() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
var n int
fmt.Fscan(in, &n)
sam := NewSuffixAutomatonGeneral()
for i := 0; i < n; i++ {
var s string
fmt.Fscan(in, &s)
sam.AddString(s, nil)
}
fmt.Fprintln(out, sam.DistinctSubstring())
fmt.Fprintln(out, sam.Size())
}
// bzoj 3926 [Zjoi2015]诸神眷顾的幻想乡 (树上本质不同路径数)
// 给出一颗叶子结点不超过 20 个的无根树,每个节点上都有一个不超过 10 的数字.
// 求树上本质不同的路径个数(两条路径相同定义为:其路径上所有节点上的数字依次相连组成的字符串相同)。
//
// 如果只建立一个SAM,会出现路径不是一条链(被 LCA 折断)的情况,不方便统计.
// !由于叶子节点仅有20个,因此从每个叶子节点开始,整棵树都会形成一个字典树。将这 棵 Trie 树拼在一起求 GSAM 即可。
func bzoj3926() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()