Cod sursa(job #3341285)

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

def solve() -> None:
    class Node:
        def __init__(self):
            self.cnt = 0
            self.end = 0
            self.sons = dict()

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

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

        if word[p] not in node.sons:
            node.sons[word[p]] = Node()

        add(node.sons[word[p]], 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

        remove(node.sons[word[p]], word, p + 1)

        return node.cnt == 0

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

        if word[p] not in node.sons:
            return 0

        return cnt_ap(node.sons[word[p]], word, p + 1)

    def len_prf(node: Node, word: str, p: int = 0) -> int:
        if (p == len(word)) or (word[p] not in node.sons) or (node.sons[word[p]].cnt == 0):
            return 0

        return 1 + len_prf(node.sons[word[p]], 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()