結果

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

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 40 ms
53,264 KB
testcase_01 AC 40 ms
53,756 KB
testcase_02 AC 36 ms
53,356 KB
testcase_03 AC 35 ms
53,360 KB
testcase_04 AC 946 ms
85,108 KB
testcase_05 AC 225 ms
85,460 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):
    self.sum += other.sum
    for c in range(26):
      rhs = other.children[c]
      if rhs:
        lhs = self.children[c]
        if lhs:
          lhs.merge(rhs)
        else:
          self.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