Refine trie method into a basic tool
dkl9

dkl9 commited on 2025-196 01:42:57
Showing 1 changed files, with 4 additions and 3 deletions.


trie.py is faster than all methods in main.py on large inputs,
and is about O(n log n) overall.
... ...
@@ -12,6 +12,7 @@ class RadixTree:
12 12
         self.children = set()
13 13
         self.parent = parent
14 14
         self.weight = 1 if label is not None else 0
15
+        self.depth = parent.depth + 1 if parent else 0
15 16
         self.height = 1
16 17
         self.usage = 0
17 18
 
... ...
@@ -86,7 +87,7 @@ class RadixTree:
86 87
 
87 88
     def best(self) -> "RadixTree":
88 89
         if self.children:
89
-            branches = minima(self.children, lambda c: (c.usage / c.weight, -c.weight))
90
+            branches = minima(self.children, lambda c: (c.usage / c.weight, -(c.weight // c.depth)))
90 91
             return min((b.best() for b in branches), key=lambda b: (len(b.full()), b.full()))
91 92
         else:
92 93
             return self
... ...
@@ -95,12 +96,12 @@ t = RadixTree()
95 96
 words = {w.strip() for w in sys.stdin}
96 97
 for w in words:
97 98
     t.add(w.strip())
99
+if "" not in words:
98 100
     t.del_empty()
99 101
 leaves = {l.full() for l in t.leaves()}
100 102
 assert leaves <= words
101 103
 assert words <= leaves
102 104
 while t.usage < t.weight:
103 105
     b = t.best()
104
-    print(b.full())
105 106
     b.use()
106
-print(str(t))
107
+    print(b.full())
107 108