Cod sursa(job #3303805)

Utilizator RosheRadutu Robert Roshe Data 18 iulie 2025 00:26:42
Problema Trie Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 2.07 kb
class Trie:
    def __init__(self):
        self.__isTerminal = 0
        self.__children = {chr(i) : None for i in range(ord('a'), ord('z') + 1)}
 
    def createNode(self):
        return Trie()
    
    def insert(self, word: str):
        node = self
        for chr in word:
            if node.__children[chr] == None:
                node.__children[chr] = self.createNode()
            node = node.__children[chr]
        node.__isTerminal += 1
 
    def checkWord(self, word: str):
        node = self
        for i, chr in enumerate(word):
            if node.__children[chr] == None:
                return False
            node = node.__children[chr]
        return node.__isTerminal
    
    def __delete(self, node, word, depth):
        if node == None:
            return None
        if depth == len(word):
            if node.__isTerminal > 0:
                node.__isTerminal -= 1
            if node.__isTerminal == 0 and all(child is None for child in node.__children.values()):
                return None
            return node
 
        char = word[depth]
        node.__children[char] = self.__delete(node.__children[char], word, depth + 1)
        if node.__isTerminal == 0 and all(child is None for child in node.__children.values()):
            return None
        return node
 
    def deleteWord(self, word: str):
        self.__delete(self, word, 0)
 
    def longestPrefix(self, word: str, depth: int):
        maxLen = 0
        node = self
        for chr in word:
            if node.__children[chr] == None:
                return maxLen
            node = node.__children[chr]
            maxLen+=1
        return maxLen
 
with open("trie.in", "r+") as f, open("trie.out", "w") as fout:
    t = Trie()
    while True:
        init = f.readline()
        if not init:
            break
        op = init[0]
        word = init[2:-1]
        if op == "0":
            t.insert(word)
        elif op == "1":
            t.deleteWord(word) 
        elif op == "2":
            print(t.checkWord(word), file = fout)
        else:
            print(t.longestPrefix(word, 0), file = fout)