-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpython.json
1460 lines (1460 loc) · 59.9 KB
/
python.json
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
{
"TrieNode": {
"prefix": "TrieNode",
"body": [
"class TrieNode:",
" \"\"\"TrieNode class can quickly process string prefixes, a common feature used in applications like autocomplete and spell checking.\"\"\"",
" _sid_cnt = 0 # sid counter, representing string index starting from 0",
"",
" def __init__(self):",
" \"\"\"Initialize children dictionary and cost. The trie tree is a 26-ary tree.\"\"\"",
" self._children_ = {}",
" self._cost = INF",
" self._is_end_of_word = False # Flag to indicate end of word",
" self._sid = -1 # Unique ID for the node, -1 if not assigned",
"",
" def add(self, word: str, cost: int) -> int:",
" \"\"\"Add a word to the trie with the associated cost and return a unique ID.\"\"\"",
" node = self",
" for c in word:",
" if c not in node._children_:",
" node._children_[c] = Std.TrieNode()",
" node = node._children_[c]",
" node._cost = Math.min(node._cost, cost)",
" node._is_end_of_word = True # Mark the end of the word",
" if node._sid < 0:",
" node._sid = self._sid_cnt",
" self._sid_cnt += 1",
" return node._sid",
"",
" def search(self, word: str) -> List[List]:",
" \"\"\"Search for prefixes of 'word' in the trie and return their lengths, costs, and sids.",
"",
" Collects ALL prefix lengths and their associated costs and sids!! ",
" Valid matches are those where node.cost != INF and node.sid != -1.",
" \"\"\"",
" node = self",
" ans = []",
" for i, c in enumerate(word):",
" if c not in node._children_:",
" break",
" node = node._children_[c]",
" ans.append([i + 1, node._cost, node._sid]) # i + 1 to denote length from start",
" return ans",
"",
" def search_exact(self, word: str) -> int:",
" \"\"\"Search for the exact word in the trie and return its cost or unique ID.\"\"\"",
" node = self",
" for c in word:",
" if c not in node._children_:",
" return INF",
" node = node._children_[c]",
" return node._cost if node._is_end_of_word else INF"
],
"description": "TrieNode"
},
"TrieNodeGraph": {
"prefix": "TrieNodeGraph",
"body": [
"class TrieNodeGraph:",
" \"\"\"TrieNode class can convert each string into an integer identifier, useful in graph theory.\"\"\"",
" _sid_cnt = 0 # sid counter, representing string index starting from 0",
" _sid_to_word_ = {} # Dictionary mapping sid to the original string",
"",
" def __init__(self):",
" \"\"\"Initialize children dictionary and cost. The trie tree is a 26-ary tree.\"\"\"",
" self._children_ = {}",
" self._is_end_of_word = False # Flag to indicate end of word",
" self._sid = -1 # Unique ID for the node, -1 if not assigned",
"",
" def add(self, word: str) -> int:",
" \"\"\"Add a word to the trie and return a unique ID.\"\"\"",
" node = self",
" for c in word:",
" if c not in node._children_:",
" node._children_[c] = Std.TrieNodeGraph()",
" node = node._children_[c]",
" node._is_end_of_word = True # Mark the end of the word",
" if node._sid < 0:",
" node._sid = self._sid_cnt",
" self._sid_cnt += 1",
" self._sid_to_word_[node._sid] = word",
" return node._sid",
"",
" def _search(self, word: str) -> int:",
" \"\"\"Search for the exact word in the trie and return its unique ID, else -1.\"\"\"",
" node = self",
" for c in word:",
" if c not in node._children_:",
" return -1",
" node = node._children_[c]",
" return node._sid if node._is_end_of_word else -1",
"",
" def get_id(self, word: str) -> int:",
" \"\"\"Retrieve the unique ID for a given word.\"\"\"",
" return self._search(word)",
"",
" def get_str(self, sid: int) -> str:",
" \"\"\"Retrieve the original string associated with a given unique ID.\"\"\"",
" return word if (word := self._sid_to_word_.get(sid)) else \"-1\""
],
"description": "TrieNodeGraph"
},
"TrieNode01": {
"prefix": "TrieNode01",
"body": [
"class TrieNode01:",
" \"\"\"",
" TrieNode01 class is a binary trie optimized for operations on binary strings.",
" Useful for problems like finding maximum XOR of two numbers in an array.",
" \"\"\"",
"",
" def __init__(self):",
" \"\"\"Initialize TrieNode01 with two children and a value.\"\"\"",
" self._children_: List = [None, None] # Only two children: 0 and 1",
" self._value: Optional[int] = None # Store the actual value if this is an end node",
" self._count = 0 # Number of numbers passing through this node",
"",
" def insert(self, num: int):",
" \"\"\"Insert a number into the binary trie.\"\"\"",
" node = self",
" for i in range(31, -1, -1): # Assuming 32-bit integers",
" bit = (num >> i) & 1",
" if not node._children_[bit]:",
" node._children_[bit] = Std.TrieNode01()",
" node = node._children_[bit]",
" node.count += 1",
" node._value = num # Store the number at the leaf node",
"",
" def find_max_xor(self, num: int) -> int:",
" \"\"\"Find the maximum XOR of 'num' with any number in the trie.\"\"\"",
" node = self",
" max_xor = 0",
" for i in range(31, -1, -1): # Assuming 32-bit integers",
" bit = (num >> i) & 1",
" toggled_bit = 1 - bit",
" if node._children_[toggled_bit]: # Prefer the toggled bit if it exists",
" max_xor = (max_xor << 1) | 1 # Current bit is 1 (since XOR with toggled bit)",
" node = node._children_[toggled_bit]",
" else:",
" max_xor = (max_xor << 1) # Current bit is 0 (since XOR with the same bit)",
" node = node._children_[bit]",
" return max_xor",
"",
" def count_equal(self, num: int) -> int:",
" \"\"\"Count the number of values in the Trie equal to the given num.\"\"\"",
" node = self",
" for i in range(31, -1, -1):",
" bit = (num >> i) & 1",
" if bit in node._children_:",
" node = node._children_[bit]",
" else:",
" return 0 # If the bit path does not exist, return 0",
" return node._count # Return the count of values equal to the given num"
],
"description": "TrieNode01"
},
"SparseTable": {
"prefix": "SparseTable",
"body": [
"class SparseTable:",
" def __init__(self, data: List, func=lambda x, y: x | y):",
" \"\"\"Initialize the Sparse Table with the given data and function.\"\"\"",
" self._func = func",
" self._st_ = [list(data)]",
" i, n = 1, len(self._st_[0])",
" while 2 * i <= n:",
" pre_ = self._st_[-1]",
" self._st_.append([func(pre_[j], pre_[j + i]) for j in range(n - 2 * i + 1)])",
" i <<= 1",
"",
" def query(self, begin: int, end: int) -> int:",
" \"\"\"Query the combined result over the interval [begin, end] using O(1).\"\"\"",
" lg = (end - begin + 1).bit_length() - 1",
" return self._func(self._st_[lg][begin], self._st_[lg][end - (1 << lg) + 1])"
],
"description": "SparseTable"
},
"StringHash": {
"prefix": "StringHash",
"body": [
"class StringHash:",
" \"\"\"A class for efficiently computing hash values of substrings within a string.\"\"\"",
"",
" def __init__(self, s: str, mod: int = 1_070_777_777):",
" \"\"\"Initialize the StringHash object with the string, base, and mod.\"\"\"",
" self._mod = mod",
" self._base = random.randint(8 * 10 ** 8, 9 * 10 ** 8)",
" self._s = s",
" self._n = len(s)",
" self._pow_base_ = [1] + Arr.array(0, self._n) # pow_base[i] = BASE ^ i",
" self._pre_hash_ = Arr.array(0, self._n + 1) # pre_hash[i] = hash(s[:i])",
" self._compute_hash()",
"",
" def _compute_hash(self):",
" \"\"\"Compute the prefix hash values and power of base values for the string.\"\"\"",
" for i, b in enumerate(self._s):",
" self._pow_base_[i + 1] = self._pow_base_[i] * self._base % self._mod",
" self._pre_hash_[i + 1] = (self._pre_hash_[i] * self._base + ord(b)) % self._mod",
"",
" def get_hash(self, l: int, r: int) -> int:",
" \"\"\"Get the hash value of the substring s[l:r] \"\"\"",
" return (self._pre_hash_[r + 1] - self._pre_hash_[l] * self._pow_base_[r - l + 1] % self._mod + self._mod) % self._mod",
"",
" def compute_hash(self, word: str) -> int:",
" \"\"\"Compute the hash value of a given word using the object's base and mod.\"\"\"",
" h = 0",
" for b in word:",
" h = (h * self._base + ord(b)) % self._mod",
" return h"
],
"description": "StringHash"
},
"PrefixSum": {
"prefix": "PrefixSum",
"body": [
"class PrefixSum:",
" def __init__(self, nums: List[int]):",
" \"\"\"Initializes the PrefixSum object with the given list of numbers.",
"",
" Args:",
" nums (List[int]): The input array of integers (0-based index).",
" \"\"\"",
" self._n = len(nums)",
" self._prefix_sum_ = Arr.array(0, self._n + 1) # 1-based index",
"",
" # Compute the prefix sum with adjusted indexing",
" for i in range(1, self._n + 1):",
" # Adjust nums index by subtracting 1 to map 1-based prefix_sum to 0-based nums",
" self._prefix_sum_[i] = self._prefix_sum_[i - 1] + nums[i - 1]",
"",
" def query(self, left: int, right: int) -> int:",
" \"\"\"Returns the sum of elements in the range [left, right]. The input coordinates is 0-based indexing.\"\"\"",
" # Convert the 0-based indices to 1-based by adding 1",
" return self._prefix_sum_[right + 1] - self._prefix_sum_[left]"
],
"description": "PrefixSum"
},
"PrefixSumTwoDim": {
"prefix": "PrefixSumTwoDim",
"body": [
"class PrefixSumTwoDim:",
" def __init__(self, matrix: List[List[int]]):",
" \"\"\"Initializes the PrefixSumTwoDim object with the given matrix.",
"",
" Args:",
" matrix (List[List[int]]): The input 2D array of integers (0-based index).",
" \"\"\"",
" self._rows = len(matrix)",
" self._cols = len(matrix[0])",
" self._prefix_sum_ = Arr.array2d(0, self._cols + 1, self._rows + 1) # 1-based index",
"",
" # Compute the prefix sum with adjusted indexing",
" for i in range(1, self._rows + 1):",
" for j in range(1, self._cols + 1):",
" # Adjust matrix indices by subtracting 1 to map 1-based prefix_sum to 0-based matrix",
" self._prefix_sum_[i][j] = matrix[i - 1][j - 1] + self._prefix_sum_[i - 1][j] + self._prefix_sum_[i][j - 1] - self._prefix_sum_[i - 1][j - 1]",
"",
" def query(self, x1: int, y1: int, x2: int, y2: int) -> int:",
" \"\"\"Returns the sum of the submatrix from (x1, y1) to (x2, y2). The input coordinates is 0-based indexing.\"\"\"",
" # Convert the 0-based indices to 1-based by adding 1",
" return self._prefix_sum_[x2 + 1][y2 + 1] - self._prefix_sum_[x1][y2 + 1] - self._prefix_sum_[x2 + 1][y1] + self._prefix_sum_[x1][y1]"
],
"description": "PrefixSumTwoDim"
},
"Bisect": {
"prefix": "Bisect",
"body": [
"class Bisect:",
" @staticmethod",
" def bisect_left(a, x, key=lambda y: y, lo=0, hi=None) -> int:",
" \"\"\"The insertion point is the first position where the element is not less than x.\"\"\"",
" if hi is None:",
" hi = len(a)",
" left, right = lo, hi",
" while left < right:",
" mid = (left + right) >> 1",
" if key(a[mid]) < x:",
" left = mid + 1",
" else:",
" right = mid",
" return left # If not found, returns hi (insertion point)",
"",
" @staticmethod",
" def bisect_right(a, x, key=lambda y: y, lo=0, hi=None) -> int:",
" \"\"\"The insertion point is the first position where the element is greater than x.\"\"\"",
" if hi is None:",
" hi = len(a)",
" left, right = lo, hi",
" while left < right:",
" mid = (left + right) >> 1",
" if key(a[mid]) <= x:",
" left = mid + 1",
" else:",
" right = mid",
" return left # If not found, returns hi (insertion point)"
],
"description": "Bisect"
},
"Func (3.8.6)": {
"prefix": "Func",
"body": [
"class Func:",
" @staticmethod",
" def find(container, value) -> int:",
" \"\"\"Returns the index of value in container or -1 if value is not found.\"\"\"",
" if isinstance(container, list):",
" try:",
" return container.index(value)",
" except ValueError:",
" return -1",
" elif isinstance(container, str):",
" return container.find(value) # type: ignore",
" ",
" @staticmethod",
" def pairwise(iterable):",
" \"\"\"Return successive overlapping pairs taken from the input iterable.\"\"\"",
" a, b = tee(iterable)",
" next(b, None)",
" return zip(a, b)"
],
"description": "Func (3.8.6) Supplement"
},
"TreeAncestor": {
"prefix": "TreeAncestor",
"body": [
"class TreeAncestor:",
" \"\"\"",
" Binary Lifting for Tree Ancestor Queries, allows us to find the 2^i-th ancestor of any node.",
" Ensure that each node has only one edge pointing to another node to apply binary lifting.",
" \"\"\"",
"",
" def __init__(self, n: int, m: int, parent: List[int]):",
" \"\"\"",
" Initializes the TreeAncestor with the given number of nodes and parent list.",
"",
" Args:",
" n (int): Number of nodes.",
" m (int): Maximum power of 2 to consider.",
" parent (List[int]): List where parent[i] is the parent of node i.",
" \"\"\"",
" # Default: m = n.bit_length(). This is because, at most, a node could have up to 2^m ancestors. However, the appearance of CYCLE may lead to m being more than n.bit_length().",
" self._n = n",
" self._m = m",
" pa_ = [[p] + Arr.array(-1, m - 1) for p in parent] # pa[i][0] = p",
" for i in range(m - 1): # handle parent nodes exclude itself.",
" for x in range(n):",
" p = pa_[x][i] # Get the 2^i-th ancestor of node x",
" if p != -1:",
" pp = pa_[p][i] # Get the 2^i-th ancestor of p, which will be the 2^(i+1)-th ancestor of x",
" pa_[x][i + 1] = pp # Set the 2^(i+1)-th ancestor of x",
" self._pa_ = pa_",
"",
" def get_kth_ancestor(self, node: int, k: int) -> int:",
" \"\"\"Returns the k-th ancestor of the given node (The starting node). If not exists, return -1\"\"\"",
" for j in range(k.bit_length()):",
" if (k >> j) & 1:",
" node = self._pa_[node][j]",
" if node < 0:",
" break",
" return node"
],
"description": "TreeAncestor"
},
"LCA": {
"prefix": "LCA",
"body": [
"class LCA:",
" \"\"\"Useing TreeAncestor calculate LCA\"\"\"",
"",
" def __init__(self, edges: List[List[int]]):",
" n = len(edges) + 1",
" m = n.bit_length()",
" g = Arr.graph(n)",
" for x, y in edges: # Node indices start from 0",
" g[x].append(y)",
" g[y].append(x)",
"",
" depth_ = Arr.array(0, n)",
" pa_ = Arr.array2d(-1, n, m)",
"",
" def _dfs(x: int, fa: int) -> None:",
" \"\"\"Depth-first search to initialize the ancestor table and depth array.\"\"\"",
" pa_[x][0] = fa # init itself",
" for y in g[x]:",
" if y != fa:",
" depth_[y] = depth_[x] + 1",
" _dfs(y, x)",
" _dfs(0, -1)",
"",
" for i in range(m - 1):",
" for x in range(n):",
" p = pa_[x][i] # Get the 2^i-th ancestor of node x",
" if p != -1:",
" pp = pa_[p][i] # Get the 2^i-th ancestor of p, which will be the 2^(i+1)-th ancestor of x",
" pa_[x][i + 1] = pp # Set the 2^(i+1)-th ancestor of x",
" self._depth_ = depth_",
" self._pa_ = pa_",
"",
" def get_kth_ancestor(self, node: int, k: int) -> int:",
" \"\"\"Returns the k-th ancestor of the given node (The starting node). That is, jump up k steps\"\"\"",
" for i in range(k.bit_length()):",
" if (k >> i) & 1:",
" node = self._pa_[node][i]",
" if node < 0:",
" break",
" return node",
"",
" def get_lca(self, x: int, y: int) -> int:",
" \"\"\"Returns the Lowest Common Ancestor (LCA) of nodes x and y.\"\"\"",
" if self._depth_[x] > self._depth_[y]:",
" x, y = y, x",
" # Bring y and x to the same depth",
" y = self.get_kth_ancestor(y, self._depth_[y] - self._depth_[x])",
" if y == x:",
" return x",
" for i in range(len(self._pa_[x]) - 1, -1, -1):",
" px, py = self._pa_[x][i], self._pa_[y][i]",
" if px != py:",
" x, y = px, py # Move both nodes up by 2^i steps",
" return self._pa_[x][0] # Return the parent of x (or y) as LCA"
],
"description": "LCA"
},
"Floyd": {
"prefix": "Floyd",
"body": [
"class Floyd:",
" \"\"\"Floyd-Warshall algorithm\"\"\"",
"",
" def __init__(self, n: int):",
" self._n = n",
" self._g_ = Arr.graph(n)",
" self.dist_ = Arr.array2d(INF, self._n, self._n)",
" self.dp_ = Arr.array(0, n)",
"",
" def add_edge(self, u: int, v: int, w: int):",
" \"\"\"Add an edge to the graph.\"\"\"",
" self._g_[u].append((v, w))",
"",
" def floyd(self):",
" \"\"\"Floyd's algorithm for finding the shortest paths between all pairs of nodes.\"\"\"",
" # Initialize distances with the given edges",
" for u in range(self._n):",
" for v, w in self._g_[u]:",
" self.dist_[u][v] = Math.min(self.dist_[u][v], w)",
"",
" # Set the diagonal to zero",
" for i in range(self._n):",
" self.dist_[i][i] = 0",
"",
" for k in range(self._n):",
" for i in range(self._n):",
" if self.dist_[i][k] > INF // 2: # If there is no path from i to k, skip",
" continue",
" for j in range(self._n):",
" if self.dist_[i][j] > self.dist_[i][k] + self.dist_[k][j]:",
" self.dist_[i][j] = self.dist_[i][k] + self.dist_[k][j]",
"",
" def floyd_01(self):",
" \"\"\"Floyd's algorithm for finding reachability between all pairs of nodes using bitwise operations.\"\"\"",
" n = self._n",
" for u in range(n):",
" self.dp_[u] |= 1 << u # Each node can reach itself",
" for v, _ in self._g_[u]:",
" self.dp_[u] |= 1 << v # Add reachable nodes based on edges",
"",
" for k in range(n):",
" for i in range(n):",
" if self.dp_[i] >> k & 1: # If i can reach k",
" self.dp_[i] |= self.dp_[k] # Then i can also reach all nodes k can reach",
"",
" def get_dist(self, x: int, y: int) -> int:",
" \"\"\"Get distance between x and y.\"\"\"",
" return self.dist_[x][y] if self.dist_[x][y] < INF // 2 else INF",
"",
" def get_dist_01(self, x: int, y: int) -> bool:",
" \"\"\"Get whether exists path between x and y.\"\"\"",
" return self.dp_[x] >> y & 1"
],
"description": "Floyd"
},
"Spfa": {
"prefix": "Spfa",
"body": [
"class Spfa:",
" def __init__(self, n: int):",
" self._n = n",
" self._g_ = Arr.graph(n)",
"",
" def add_edge(self, u: int, v: int, w: int):",
" \"\"\"Add an edge to the graph.\"\"\"",
" self._g_[u].append((v, w))",
"",
" def spfa(self, s: int) -> List[int]:",
" \"\"\"SPFA (Shortest Path Faster Algorithm) for finding the shortest path in a graph.\"\"\"",
" dist = Arr.array(INF, self._n)",
" st = Arr.array(0, self._n)",
" q = deque()",
"",
" dist[s] = 0",
" q.appendleft(s)",
" st[s] = 1",
"",
" while q:",
" u = q.pop()",
" st[u] = 0",
" for v, w in self._g_[u]:",
" if dist[v] > dist[u] + w:",
" dist[v] = dist[u] + w",
" if st[v] == 0:",
" q.appendleft(v)",
" st[v] = 1",
"",
" return dist"
],
"description": "Spfa"
},
"Dijkstra": {
"prefix": "Dijkstra",
"body": [
"class Dijkstra:",
" \"\"\"Dijkstra's algorithm for finding the shortest path in a weighted graph, designed to compute various properties related to the shortest paths from a source node.\"\"\"",
"",
" def __init__(self, n: int, val_: List):",
" self.n = n # Number of nodes in the graph",
" self.val_ = val_ # Node values (weights associated with each node)",
" self.g_ = Arr.graph(n) # Adjacency list to store the graph",
" self.dist_ = Arr.array(INF, n) # Shortest distance from the source to each node",
" self.sum_ = Arr.array(0, n) # Sum of node values along the shortest path",
" self.cnt_ = Arr.array(0, n) # Count of shortest paths",
" self.pre_ = Arr.array(0, n) # Predecessor node in the shortest path",
" self.num_ = Arr.array(0, n) # Number of nodes in the shortest path",
"",
" def add_edge(self, u: int, v: int, w: int):",
" \"\"\"Add an edge to the graph.\"\"\"",
" self.g_[u].append((v, w))",
"",
" def dijkstra(self, s: int):",
" \"\"\"Dijkstra's algorithm for finding the shortest path in a graph.",
" This method calculates the shortest distances, maximizes the sum of node values (`val_`) along the paths, and minimizes the number of edges (`num_`) used in the paths. Additionally, it counts the number of distinct shortest paths to each node.\"\"\"",
" st_ = Arr.array(0, self.n)",
" q = []",
"",
" self.dist_[s] = 0",
" self.sum_[s] = self.val_[s]",
" self.cnt_[s] = self.num_[s] = 1",
" heappush(q, (0, s))",
"",
" while q:",
" _, u = heappop(q)",
" if st_[u]:",
" continue",
" st_[u] = 1",
" for v, w in self.g_[u]:",
" if self.dist_[v] > self.dist_[u] + w:",
" self.dist_[v] = self.dist_[u] + w",
" self.pre_[v] = u",
" self.sum_[v] = self.sum_[u] + self.val_[v]",
" self.num_[v] = self.num_[u] + 1",
" self.cnt_[v] = self.cnt_[u]",
" heappush(q, (self.dist_[v], v))",
" elif self.dist_[v] == self.dist_[u] + w:",
" self.cnt_[v] += self.cnt_[u]",
" if self.sum_[u] > self.sum_[self.pre_[v]]:",
" self.pre_[v] = u",
" self.sum_[v] = self.sum_[u] + self.val_[v]",
" self.num_[v] = self.num_[u] + 1",
" heappush(q, (self.dist_[v], v))",
" elif self.sum_[u] == self.sum_[self.pre_[v]] and self.num_[v] > self.num_[u] + 1:",
" self.pre_[v] = u",
" self.num_[v] = self.num_[u] + 1",
" heappush(q, (self.dist_[v], v))"
],
"description": "Dijkstra"
},
"Dijkstra(simple)": {
"prefix": "Dijkstra(simple)",
"body": [
"class Dijkstra:",
" \"\"\"Dijkstra's algorithm for finding the shortest path in a weighted graph, designed to compute various properties related to the shortest paths from a source node.\"\"\"",
"",
" def __init__(self):",
" self.g_ = defaultdict(list) # Adjacency list to store the graph",
" self.dist_ = defaultdict(lambda: INF)",
"",
" def add_edge(self, u: int, v: int, w: int):",
" \"\"\"Add an edge to the graph.\"\"\"",
" self.g_[u].append((v, w))",
"",
" def dijkstra(self, s: int):",
" \"\"\"Dijkstra's algorithm for finding the shortest path in a graph.\"\"\"",
" st_ = defaultdict(lambda: False)",
" q = []",
" self.dist_[s] = 0",
" heappush(q, (0, s))",
"",
" while q:",
" _, u = heappop(q)",
" if st_[u]:",
" continue",
" st_[u] = True",
" for v, w in self.g_[u]:",
" if self.dist_[v] > self.dist_[u] + w:",
" self.dist_[v] = self.dist_[u] + w",
" heappush(q, (self.dist_[v], v))"
],
"description": "Dijkstra(simple)"
},
"Str": {
"prefix": "Str",
"body": [
"class Str:",
" atoi = staticmethod(lambda x: ord(x.upper()) - 65) # A -> 0",
" itoa = staticmethod(lambda x: ascii_uppercase[x]) # 0 -> A",
" removeprefix = staticmethod(lambda s, prefix: s[len(prefix):] if s.startswith(prefix) else s)",
" removesuffix = staticmethod(lambda s, suffix: s[:-len(suffix)] if s.endswith(suffix) else s)"
],
"description": "Str"
},
"IO": {
"prefix": "IO",
"body": [
"class IO:",
" input = staticmethod(lambda: stdin.readline().strip())",
" read = staticmethod(lambda: map(int, IO.input().split()))",
" read_list = staticmethod(lambda: list(IO.read()))",
" read_mixed = staticmethod(lambda *types: [t(v) for t, v in zip(types, IO.input().split())])"
],
"description": "IO"
},
"Mod": {
"prefix": "Mod",
"body": [
"class Mod:",
" add = staticmethod(lambda *args: (lambda result=0: [(result := (result + num) % MOD) for num in args] and result)())",
" sub = staticmethod(lambda a, b: (a - b + MOD) % MOD)",
" mul = staticmethod(lambda *args: (lambda result=1: [(result := (result * num) % MOD) for num in args] and result)())",
" div = staticmethod(lambda a, b: (a * pow(b, MOD - 2, MOD)) % MOD)",
" mod = staticmethod(lambda a: (a % MOD + MOD) % MOD)"
],
"description": "Mod"
},
"BipartiteMatcher": {
"prefix": "BipartiteMatcher",
"body": [
"class BipartiteMatcher:",
" def __init__(self, n: int):",
" \"\"\"Initialize the BipartiteMatcher with n nodes.\"\"\"",
" self._n = n",
" self._match_ = Arr.array(0, self._n)",
" self._st_ = Arr.array(0, self._n)",
" self._g_ = Arr.graph(self._n)",
"",
" def add_edge(self, u: int, v: int):",
" \"\"\"Add an edge between node u and node v.\"\"\"",
" self._g_[u].append(v)",
"",
" def find(self, u: int) -> bool:",
" \"\"\"Find an augmenting path starting from node u.\"\"\"",
" for v in self._g_[u]:",
" if self._st_[v] == 0:",
" self._st_[v] = 1",
" if self._match_[v] == 0 or self.find(self._match_[v]):",
" self._match_[v] = u",
" return True",
" return False",
"",
" def max_matching(self) -> int:",
" \"\"\"Compute the maximum matching in the bipartite graph.\"\"\"",
" res = 0",
" for i in range(self._n):",
" self._st_ = Arr.array(0, self._n)",
" if self.find(i):",
" res += 1",
" return res"
],
"description": "BipartiteMatcher"
},
"SegTree": {
"prefix": "SegTree",
"body": [
"class SegTree:",
" \"\"\"",
" A segment tree based on dynamic binary tree algorithm. ",
" Supports passing callback functions `f1` and `f2` to handle range queries (RMQ) such as range sum, range maximum, and range minimum.",
" \"\"\"",
"",
" def __init__(self, f1: Callable, f2: Callable, l: int, r: int, v: int = 0):",
" \"\"\"",
" Initializes the segment tree [left, right).",
"",
" Example functions:",
" Segment Sum:",
" f1 = lambda a, b: a + b",
" f2 = lambda a, n: a * n",
" Segment Maximum:",
" f1 = lambda a, b: Math.max(a, b)",
" f2 = lambda a, n: a",
" Segment Minimum:",
" f1 = lambda a, b: Math.min(a, b)",
" f2 = lambda a, n: a",
" Args:",
" f1: Function for combining segment values. (merge values from different intervals)",
" f2: Function for applying values to segments. (Spread a value to an interval)",
" l (int): Left boundary of the segment.",
" r (int): Right boundary of the segment.",
" v (int): Initial value for the segment.",
" \"\"\"",
" self._default = v # Default value for the segments",
" self._ans = f2(v, r-l) # Current result of the segment",
" self._f1 = f1",
" self._f2 = f2",
" self._l = l # left",
" self._r = r # right",
" self._v = v # init value",
" self._lazy_tag = 0 # Lazy tag",
" self._left = None # SubTree(left, bottom)",
" self._right = None # SubTree(right, bottom)",
"",
" def __repr__(self) -> str:",
" \"\"\"Returns values of the segment.\"\"\"",
" anss = []",
" for i in range(self._l, self._r):",
" anss.append(str(self.query(i, i + 1)))",
" return \"seg: \" + \" \".join(anss)",
"",
" @property",
" def _mid_h(self) -> int:",
" \"\"\"Returns the midpoint of the segment.\"\"\"",
" return self._l + self._r >> 1",
"",
" def _create_subtrees(self):",
" \"\"\"Creates left and right subtrees if they do not exist.\"\"\"",
" midh = self._mid_h",
" if not self._left and midh > self._l:",
" self._left = Std.SegTree(self._f1, self._f2, self._l, midh, self._default)",
" if not self._right:",
" self._right = Std.SegTree(self._f1, self._f2, midh, self._r, self._default)",
"",
" def build(self, arr: List[int]) -> int:",
" \"\"\"",
" Initializes the segment tree with values from arr.",
"",
" Args:",
" arr: List of values to initialize the segment tree.",
"",
" Returns:",
" The combined value of the segment tree.",
" \"\"\"",
" m0 = arr[0]",
" self._lazy_tag = 0",
" if self._r == self._l + 1:",
" self._v = m0",
" self._ans = self._f2(m0, len(arr))",
" return self._ans",
" self._v = '#'",
" midh = self._mid_h",
" self._create_subtrees()",
" self._ans = self._f1(self._left.build(arr[:midh - self._l]), self._right.build(arr[midh - self._l:]))",
" return self._ans",
"",
" def cover_seg(self, l: int, r: int, v: int) -> int:",
" \"\"\"",
" Covers the segment [left, right) with value v.",
"",
" Args:",
" l (int): Left boundary of the cover range.",
" r (int): Right boundary of the cover range.",
" v: Value to cover the segment with.",
"",
" Returns:",
" The combined value of the segment tree.",
" \"\"\"",
" if self._v == v or l >= self._r or r <= self._l:",
" return self._ans",
" if l <= self._l and r >= self._r:",
" self._v = v",
" self._lazy_tag = 0",
" self._ans = self._f2(v, self._r - self._l)",
" return self._ans",
" self._create_subtrees()",
" if self._v != '#':",
" self._left._v = self._v",
" self._left._ans = self._f2(self._v, self._left._r - self._left._l)",
" self._right._v = self._v",
" self._right._ans = self._f2(self._v, self._right._r - self._right._l)",
" self._v = '#'",
" # push up",
" self._ans = self._f1(self._left.cover_seg(l, r, v), self._right.cover_seg(l, r, v))",
" return self._ans",
"",
" def inc_seg(self, l: int, r: int, v: int) -> int:",
" \"\"\"",
" Increases the segment [left, right) by value v.",
"",
" Args:",
" l (int): Left boundary of the increase range.",
" r (int): Right boundary of the increase range.",
" v: Value to increase the segment by.",
"",
" Returns:",
" The combined value of the segment tree.",
" \"\"\"",
" if v == 0 or l >= self._r or r <= self._l:",
" return self._ans",
" if l <= self._l and r >= self._r:",
" if self._v == '#':",
" self._lazy_tag += v",
" else:",
" self._v += v",
" self._ans += self._f2(v, self._r - self._l)",
" return self._ans",
" self._create_subtrees()",
" if self._v != '#':",
" self._left._v = self._v",
" self._left._ans = self._f2(self._v, self._left._r - self._left._l)",
" self._right._v = self._v",
" self._right._ans = self._f2(self._v, self._right._r - self._right._l)",
" self._v = '#'",
" self._pushdown()",
" # push up",
" self._ans = self._f1(self._left.inc_seg(l, r, v), self._right.inc_seg(l, r, v))",
" return self._ans",
"",
" def inc_idx(self, idx: int, v: int) -> int:",
" \"\"\"",
" Increases the value at index idx by value v.",
"",
" Args:",
" idx (int): Index to increase.",
" v: Value to increase by.",
"",
" Returns:",
" The combined value of the segment tree.",
" \"\"\"",
" if v == 0 or idx >= self._r or idx < self._l:",
" return self._ans",
" if idx == self._l == self._r - 1:",
" self._v += v",
" self._ans += self._f2(v, 1)",
" return self._ans",
" self._create_subtrees()",
" if self._v != '#':",
" self._left._v = self._v",
" self._left._ans = self._f2(self._v, self._left._r - self._left._l)",
" self._right._v = self._v",
" self._right._ans = self._f2(self._v, self._right._r - self._right._l)",
" self._v = '#'",
" self._pushdown()",
" # push up",
" self._ans = self._f1(self._left.inc_idx(idx, v), self._right.inc_idx(idx, v))",
" return self._ans",
"",
" def _pushdown(self):",
" \"\"\"Propagates the lazy tag to the child nodes.\"\"\"",
" if self._lazy_tag != 0:",
" if self._left._v != '#':",
" self._left._v += self._lazy_tag",
" else:",
" self._left._lazy_tag += self._lazy_tag",
" self._left._ans += self._f2(self._lazy_tag, self._left._r - self._left._l)",
" if self._right._v != '#':",
" self._right._v += self._lazy_tag",
" else:",
" self._right._lazy_tag += self._lazy_tag",
" self._right._ans += self._f2(self._lazy_tag, self._right._r - self._right._l)",
" self._lazy_tag = 0",
"",
" def query(self, l: int, r: int) -> int:",
" \"\"\"",
" Queries the range [left, right) for the combined value.",
"",
" Args:",
" l (int): Left boundary of the query range.",
" r (int): Right boundary of the query range.",
"",
" Returns:",
" The combined value of the range.",
" \"\"\"",
" if l >= r:",
" return 0",
" if l <= self._l and r >= self._r:",
" return self._ans",
" if self._v != '#':",
" return self._f2(self._v, Math.min(self._r, r) - Math.max(self._l, l)) # the overlapping length",
" self._create_subtrees()",
" midh = self._mid_h",
" self._pushdown()",
" ans_ = []",
" if l < midh:",
" ans_.append(self._left.query(l, r))",
" if r > midh:",
" ans_.append(self._right.query(l, r))",
" return reduce(self._f1, ans_)",
"",
" @staticmethod",
" def discretize(array):",
" \"\"\"Discretize the array and return the mapping dictionary. Index starts from 1\"\"\"",
" sorted_unique = sorted(set(array))",
" mapping = {val: idx + 1 for idx, val in enumerate(sorted_unique)}",
" return [mapping[val] for val in array], mapping"
],
"description": "SegTree"
},
"KMP": {
"prefix": "KMP",
"body": [
"class KMP:",
" def __init__(self, t: str):",
" \"\"\"Initializes the KMP object with a text string.\"\"\"",
" self.t = t",
"",
" def _calc_mml(self, p: str) -> List[int]:",
" \"\"\"Constructs the maximum match lengths table for the pattern.",
"",
" Args:",
" p (str): The pattern string for which the table is constructed.",
"",
" Returns:",
" List[int]: The list of maximum match lengths for the pattern string.",
" \"\"\"",
" mml_, j = Arr.array(0, len(p)), 0 # Initialize max match lengths array and max length",
" for i in range(1, len(p)):",
" while j > 0 and p[j] != p[i]: # Backtrack to find the longest prefix which is also a suffix",
" j = mml_[j - 1]",
" if p[j] == p[i]: # If characters match, extend the length of the prefix",
" j += 1",
" mml_[i] = j # Store the max length at this position",
" return mml_",
"",
" def search(self, p: str) -> List[int]:",
" \"\"\"Searches for all occurrences of the pattern in the text.",
"",
" Args:",
" p (str): The pattern string to search for within the text.",
"",
" Returns:",
" List[int]: A list of starting indices where the pattern is found in the text.",
" \"\"\"",
" mml_ = self._calc_mml(p) # Compute max match lengths for the pattern",
" pos_ = [] # List to store the starting indices of matches",
" cnt = 0 # Number of characters currently matched",
" for i in range(len(self.t)):",
" while cnt > 0 and p[cnt] != self.t[i]: # If there's a mismatch, backtrack using max match lengths table",
" cnt = mml_[cnt - 1]",
" if p[cnt] == self.t[i]: # If characters match, advance the match length",
" cnt += 1",
" if cnt == len(p): # If a full match is found, record the start position and backtrack",
" pos_.append(i - len(p) + 1)",
" cnt = mml_[cnt - 1]",
"",
" return pos_"
],
"description": "KMP"
},
"Z(EXKMP)": {
"prefix": "EXKMP",
"body": [
"class EXKMP:",
" def __init__(self, s: str):",
" \"\"\"Initializes the Z object with a string.\"\"\"",
" self.s = s",
"",
" def calc_z(self) -> list[int]:",
" \"\"\"Constructs the Z-array for the string.",
"",
" Returns:",
" List[int]: The Z-array representing the longest prefix matches for each index.",
" \"\"\"",
" n = len(self.s)",
" z = Arr.array(0, n)",
" box_l = box_r = 0 # Initialize the Z-box boundaries",
" for i in range(1, n):",
" if i <= box_r:",
" # Use previously computed Z-values to skip unnecessary comparisons",
" z[i] = Math.min(z[i - box_l], box_r - i + 1)",
" while i + z[i] < n and self.s[z[i]] == self.s[i + z[i]]:",
" # Expand the Z-box if characters match",
" z[i] += 1",
" box_l, box_r = i, i + z[i] - 1 # Update the Z-box boundaries",
" return z"
],
"description": "Z(EXKMP)"
},
"Comb": {
"prefix": "Comb",
"body": [
"class Comb:",
" def __init__(self, max_n: int):",
" \"\"\"Initialize and precompute factorials and inverse factorials up to max_n.\"\"\"",
" self._max_n = max_n",
" self._fac_: List[int] = Arr.array(1, max_n + 1)",
" self._inv_fac_: List[int] = Arr.array(1, max_n + 1)",
" self._init_factorials()",
"",
" def _init_factorials(self):",
" \"\"\"Precompute factorials and inverse factorials.\"\"\"",
" for i in range(2, self._max_n + 1):",
" self._fac_[i] = Math.Mod.mul(self._fac_[i - 1], i)",
" self._inv_fac_[self._max_n] = pow(self._fac_[self._max_n], MOD - 2, MOD)",