# KMP 模板 defcalc_max_match(self, s: str) -> List[int]: match = [0] * len(s) c = 0 for i inrange(1, len(s)): v = s[i] while c and s[c] != v: c = match[c - 1] if s[c] == v: c += 1 match[i] = c returnmatch
# KMP 模板 # 返回 text 中出现了多少次 pattern(允许 pattern 重叠) defkmp_search(self, text: str, pattern: str) -> int: match = self.calc_max_match(pattern) match_cnt = c = 0 for i, v inenumerate(text): v = text[i] while c and pattern[c] != v: c = match[c - 1] if pattern[c] == v: c += 1 if c == len(pattern): match_cnt += 1 c = match[c - 1] return match_cnt
# 矩阵乘法 defmultiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]: c = [[0, 0], [0, 0]] for i inrange(2): for j inrange(2): c[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % (10 ** 9 + 7) return c
# 矩阵快速幂 defpow(self, a: List[List[int]], n: int) -> List[List[int]]: res = [[1, 0], [0, 1]] while n: if n % 2: res = self.multiply(res, a) a = self.multiply(a, a) n //= 2 return res