deepcopy耗时真的很大
import time
from typing import List, Dict, Union
exist_cuts: Dict[int, int] = {
0: 0,
1: 1,
2: 5,
3: 8
}
cut_p_maxcache: Dict[int, int] = dict()
cut_cord_maxcache: Dict[int, "Cut"] = dict()
class Cut:
def __init__(self, left: Union["Cut", None], right: Union["Cut", None], length: int = 0, p: int = 0):
self.left: Union["Cut", None] = left
self.right: Union["Cut", None] = right
self.length: int = length
self.p: int = p
def cal_p(self) -> int:
if self.length in cut_p_maxcache.keys():
self.p = cut_p_maxcache[self.length]
return self.p
if self.left is None and self.right is None:
self.p = exist_cuts[self.length]
return self.p
if self.left is None:
left_p = 0
else:
left_p = self.left.cal_p()
if self.right is None:
right_p = 0
else:
right_p = self.right.cal_p()
self.p = left_p + right_p
return self.p
def __repr__(self):
return f"[left:{self.left.length if self.left else 0}, right:{self.right.length if self.right else 0}, length:{self.length}, p:{self.p}]"
def to_structure(self) -> str:
if self.left is None and self.right is None:
return f"{self.length}"
if self.left is None:
left_s = ""
else:
left_s = self.left.to_structure()
if self.right is None:
right_s = ""
else:
right_s = self.right.to_structure()
return f"{left_s}+{right_s}"
def copy(self) -> "Cut":
left_is_none: bool = self.left is None
right_is_none: bool = self.right is None
if left_is_none and right_is_none:
return self
if left_is_none:
left = self.left
else:
left = self.left.copy()
if right_is_none:
right = self.right
else:
right = self.right.copy()
return Cut(left, right, self.length, self.p)
def cut_rod(n: int) -> Cut:
if n in exist_cuts.keys():
return Cut(None, None, n, exist_cuts[n])
else:
if n in cut_cord_maxcache.keys():
return cut_cord_maxcache[n].copy()
cuts: List[Cut] = []
half_n = int(n / 2) + 1
for i in range(1, half_n):
cut = Cut(cut_rod(i), cut_rod(n - i), length=n)
cuts.append(cut)
max_cut: Cut = max(cuts, key=lambda cut: cut.cal_p())
cut_p_maxcache[max_cut.length] = max_cut.p
cut_cord_maxcache[max_cut.length] = max_cut
return max_cut
if __name__ == "__main__":
time_start: float = time.time()
cut = cut_rod(400)
print(cut.p)
print(cut.to_structure())
time_end: float = time.time()
print(f"time_use: {time_end - time_start}")