結果

問題 No.2761 Substitute and Search
ユーザー maguroflymagurofly
提出日時 2024-05-05 17:11:24
言語 PyPy3
(7.3.15)
結果
MLE  
実行時間 -
コード長 1,825 bytes
コンパイル時間 140 ms
コンパイル使用メモリ 82,484 KB
実行使用メモリ 848,604 KB
最終ジャッジ日時 2024-05-07 04:53:42
合計ジャッジ時間 5,803 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 37 ms
53,876 KB
testcase_01 AC 37 ms
54,108 KB
testcase_02 AC 38 ms
52,952 KB
testcase_03 AC 41 ms
53,160 KB
testcase_04 AC 1,003 ms
85,216 KB
testcase_05 AC 227 ms
85,860 KB
testcase_06 MLE -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

class TrieNode:
  __slots__ = ("sum", "children")

  def __init__(self):
    self.sum = 0
    self.children = [None] * 26

  def merge(self, other):
    stack = [(self, other)]
    while stack:
      a, b = stack.pop()
      a.sum += b.sum
      for c in range(26):
        rhs = b.children[c]
        if rhs:
          lhs = a.children[c]
          if lhs:
            stack.append((lhs, rhs))
          else:
            a.children[c] = rhs

class Trie:
  __slots__ = ("root", "subst")

  def __init__(self, l):
    self.root = TrieNode()
    self.subst = [[i % 26] for i in range(l * 26)]
  
  def add(self, s):
    cur = self.root
    cur.sum += 1
    for k in range(len(s)):
      c = ord(s[k]) - 0x61
      if not cur.children[c]:
        node = TrieNode()
        cur.children[c] = node
      cur = cur.children[c]
      cur.sum += 1
  
  def substitute(self, k, c, d):
      c = ord(c) - 0x61
      d = ord(d) - 0x61
      x, y = self.subst[k * 26 + d], self.subst[k * 26 + c]
      if len(x) < len(y): x, y = y, x
      for v in y: x.append(v)
      self.subst[k * 26 + d] = x
      self.subst[k * 26 + c] = []
  
  def search(self, s):
    cur = self.root
    for k in range(len(s)):
      d = ord(s[k]) - 0x61
      last = None
      for c in self.subst[k * 26 + d]:
        node = cur.children[c]
        if node:
          if last:
            last.merge(node)
            cur.children[c] = None
          else:
            last = node
      if not last:
        return 0
      cur = last
    return cur.sum

N, L, Q = map(int, input().split())
trie = Trie(L)
for _ in range(N):
  trie.add(input().strip())

for _ in range(Q):
  query = input().strip().split()
  if query[0] == "1":
    k = int(query[1]) - 1
    c = query[2]
    d = query[3]
    trie.substitute(k, c, d)
  else:
    print(trie.search(query[1]))
0