Cod sursa(job #3338229)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 1 februarie 2026 18:23:25
Problema Trie Scor 100
Compilator py Status done
Runda Arhiva educationala Marime 2.02 kb
class Node:
    def __init__(self):
        self.children = [None] * 26
        self.cnt_ap = 0
        self.cnt_w = 0
    
    def add(self, node, string):
        if len(string) == 0:
            node.cnt_ap += 1
            node.cnt_w += 1
            return

        node.cnt_ap += 1

        letter_idx = ord(string[0]) - ord('a')
        child = node.children[letter_idx]
        if child == None:
            child = Node()

        self.add(child, string[1:])
        node.children[letter_idx] = child

    def delete(self, node, string):
        node.cnt_ap -= 1

        if len(string) == 0:
            node.cnt_w -= 1
            return

        letter_idx = ord(string[0]) - ord('a')
        self.delete(node.children[letter_idx], string[1:])
    
    def get_cnt_ap(self, node, word):
        if node.cnt_ap == 0:
            return 0

        if len(word) == 0:
            return node.cnt_w

        letter_idx = ord(word[0]) - ord('a')
        if node.children[letter_idx] == None:
            return 0

        return self.get_cnt_ap(node.children[letter_idx], word[1:])
    
    def longest_pref(self, node, word):
        if node.cnt_ap == 0:
            return -1

        if len(word) == 0:
            return 0

        letter_idx = ord(word[0]) - ord('a')
        if node.children[letter_idx] == None:
            return 0

        return 1 + self.longest_pref(node.children[letter_idx], word[1:])


def main():
    commands = []
    with open("trie.in", "r") as in_file:
        commands = in_file.readlines()
    
    out_file = open("trie.out", "w")
    trie = Node()

    for command in commands:
        typ, arg = command.strip().split()
        typ = int(typ)

        if typ == 0:
            trie.add(trie, arg)
        elif typ == 1:
            trie.delete(trie, arg)
        elif typ == 2:
            ans = trie.get_cnt_ap(trie, arg)
            out_file.write(f'{ans}\n')
        else:
            ans = trie.longest_pref(trie, arg)
            out_file.write(f'{ans}\n')

    out_file.close()


if __name__ == "__main__":
    main()