Cod sursa(job #3341286)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 18 februarie 2026 20:40:47
Problema Trie Scor 100
Compilator py Status done
Runda Arhiva educationala Marime 1.96 kb
import json
import operator
from dataclasses import dataclass

Alf = 26

def solve() -> None:
    class Node:
        def __init__(self):
            self.cnt = 0
            self.end = 0
            self.sons = [None for _ in range(Alf)]

    def add(node: Node, word: str, p: int = 0) -> None:
        node.cnt += 1

        if p == len(word):
            node.end += 1
            return

        if node.sons[ord(word[p]) - ord('a')] is None:
            node.sons[ord(word[p]) - ord('a')] = Node()

        add(node.sons[ord(word[p]) - ord('a')], word, p + 1)

    def remove(node: Node, word: str, p: int = 0) -> bool:
        node.cnt -= 1

        if p == len(word):
            node.end -= 1
            return node.cnt == 0

        if remove(node.sons[ord(word[p]) - ord('a')], word, p + 1):
            node.sons[ord(word[p]) - ord('a')] = None

        return node.cnt == 0

    def cnt_ap(node: Node, word: str, p: int = 0) -> int:
        if p == len(word):
            return node.end

        if node.sons[ord(word[p]) - ord('a')] is None:
            return 0

        return cnt_ap(node.sons[ord(word[p]) - ord('a')], word, p + 1)

    def len_prf(node: Node, word: str, p: int = 0) -> int:
        if (p == len(word)) or (node.sons[ord(word[p]) - ord('a')] == None):
            return 0

        return 1 + len_prf(node.sons[ord(word[p]) - ord('a')], word, p + 1)


    root = Node()

    with open('trie.in', 'r') as f:
        with open('trie.out', 'w') as w:
            for line in f:
                op_s, word = line.strip().split(' ')
                op = int(op_s)

                if op == 0:
                    add(root, word)
                elif op == 1:
                    remove(root, word)
                elif op == 2:
                    w.write(f'{cnt_ap(root, word)}\n')
                else:
                    w.write(f'{len_prf(root, word)}\n')


if __name__ == '__main__':
    solve()