From 807de4ca6598d25f17072a7a5dd54fb578625f47 Mon Sep 17 00:00:00 2001 From: Dukantic Date: Thu, 10 Apr 2025 15:55:13 +0200 Subject: [PATCH] =?UTF-8?q?creat=20tree=20O(n=C2=B2)=20->=20O(nlog(n))?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/node.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/node.rs b/src/node.rs index 9f19375..e805748 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeSet; use std::collections::HashMap; use std::collections::VecDeque; @@ -8,7 +9,25 @@ pub struct Node { pub n: i32, pub path: String, } +impl PartialEq for Node { + fn eq(&self, other: &Self) -> bool { + self.n == other.n + } +} +impl Eq for Node {} + +impl PartialOrd for Node { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Node { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.n.cmp(&other.n) + } +} impl Node { pub fn new() -> Self { Node { @@ -65,13 +84,19 @@ pub fn tree_to_map(root: &mut Node, char_to_bin: bool) -> HashMap) -> Node { while nodes.len() > 1 { - nodes.sort_by_key(|node| node.n); + //nodes.sort_by_key(|node| node.n); let mut new_root = Node::new(); let l = nodes.remove(0); let r = nodes.remove(0); new_root.set_counter(l.n + r.n); new_root.insert(l, r); - nodes.push(new_root); + //nodes.push(new_root); + match nodes.binary_search(&new_root) { + Ok(_) => {} + Err(pos) => { + nodes.insert(pos, new_root); + } + } } nodes.pop().unwrap() }