From e6187a1aa3564a4f7278bd16c459afa361c68cf9 Mon Sep 17 00:00:00 2001 From: tgyuu-An Date: Wed, 20 Mar 2024 00:32:28 +0900 Subject: [PATCH] 2024-03-20 --- tgyuuAn/README.md | 1 + .../AB.py" | 80 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 "tgyuuAn/\355\212\270\353\235\274\354\235\264/AB.py" diff --git a/tgyuuAn/README.md b/tgyuuAn/README.md index f608a203..e95feed4 100644 --- a/tgyuuAn/README.md +++ b/tgyuuAn/README.md @@ -43,4 +43,5 @@ | 39차시 | 2023.02.18 | DP | | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/139 | 40차시 | 2023.02.21 | DP | 입대 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/142 | 41차시 | 2023.03.04 | DP | 자두나무 | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/148 +| 46차시 | 2023.03.20 | 트라이 | AB | https://github.com/AlgoLeadMe/AlgoLeadMe-1/pull/165 --- diff --git "a/tgyuuAn/\355\212\270\353\235\274\354\235\264/AB.py" "b/tgyuuAn/\355\212\270\353\235\274\354\235\264/AB.py" new file mode 100644 index 00000000..6ae80188 --- /dev/null +++ "b/tgyuuAn/\355\212\270\353\235\274\354\235\264/AB.py" @@ -0,0 +1,80 @@ +import sys +from collections import defaultdict + +class Node(): + def __init__(self, key = None): + self.key = key + self.count = 0 + self.children = {} + +class Tries(): + def __init__(self): + self.head = Node(None) + + def add(self, element): + now = self.head + + for char in element: + if char not in now.children: + now.children[char] = Node(char) + + now = now.children[char] + now.count += 1 + + def delete(self, element): + now = self.head + + for char in element: + child = now.children[char] + child.count -= 1 + if child.count == 0: del now.children[char] + now = child + + def find(self, element): + now = self.head + dic = defaultdict(int) + + string = "" + for char in element: + if char not in now.children: return dic + + string = string + char + now = now.children[char] + dic[string] = now.count + + return dic + +def input(): return sys.stdin.readline().rstrip() + +def query(method, target, element): + if method == "add": target.add(element) + + if method == "delete": target.delete(element) + + if method == "find": + n = len(element) + a_result = A.find(element) + b_result = B.find(element[::-1]) + + answer = 0 + for a_len in range(1,n): + answer += a_result[element[:a_len]] * b_result[element[:a_len-1:-1]] + + print(answer) + +N = int(input()) +A = Tries() +B = Tries() +method, target, element = "", "", "" + +for _ in range(N): + _input = input() + if _input[:4] == "find": + method,element = _input.split() + query(method, A, element) + + else: + method, target, element = _input.split() + + if target == "A": query(method, A, element) + else: query(method, B, element[::-1]) \ No newline at end of file