#MMA Contest 015 - K Make a Sequence #static Li Chao Treeで通ったのでdynamic Li Chao Treeで通す #動的Li Chao Tree class dynamic_Li_Chao_Tree: def __init__(self, min_x, max_x): #定義域 [min_x, max_x]内でのみ正確に動作する #_C[i]: (左子のid, 右子のid) 親のidは保持しない #_S[i]: (Lt, mid, Rt) 区間は閉区間[Lt, Rt]で扱う Lt, Rt = -1, 0 while min_x < Lt: Lt = Lt * 2 while Rt < max_x: Rt = Rt * 2 + 1 self._C = [(None, None)] self._S = [(Lt, -1, Rt)] self._L = [None] def _f(self, line, x): return line[0] * x + line[1] def _get_child(self, index, get_left = True): #子のidを返す。子が存在しなければ作る c_Lt, c_Rt = self._C[index] Lt, mid, Rt = self._S[index] if get_left: if c_Lt != None: return c_Lt self._C[index] = (len(self._S), c_Rt) self._S.append((Lt, (Lt + mid) // 2, mid)) else: if c_Rt != None: return c_Rt self._C[index] = (c_Lt, len(self._S)) self._S.append((mid + 1, (mid + 1 + Rt) // 2, Rt)) self._C.append((None, None)) self._L.append(None) return len(self._S) - 1 def _add_line(self, line, i): #node iとその子に線分を追加 Q = [(i, line)] while Q: i, line = Q.pop() if self._L[i] == None: self._L[i] = line continue Lt, mid, Rt = self._S[i] hL = self._f(line, Lt ) < self._f(self._L[i], Lt ) hM = self._f(line, mid) < self._f(self._L[i], mid) hR = self._f(line, Rt ) < self._f(self._L[i], Rt ) if hL == hR == True: self._L[i] = line continue if hL == hR == False: continue if hM == line: self._L[i], line = line, self._L[i] if hL != hM: #左子を作り降りる Q.append((self._get_child(i, True), line)) else: Q.append((self._get_child(i, False), line)) def add_line(self, line, x_Lt = None, x_Rt = None): #半開区間[x_Lt, x_Rt)に線分追加 if x_Lt == x_Rt == None: self._add_line(line, 0) return x_Lt = self._S[0][0] if x_Lt == None else x_Lt x_Rt = self._S[0][2] if x_Rt == None else x_Rt - 1 Q = [(0, line, x_Lt, x_Rt)] while Q: i, line, x_Lt, x_Rt = Q.pop() Lt, mid, Rt = self._S[i] if x_Lt > x_Rt or x_Rt < Lt or Rt < x_Lt: continue x_Lt = max(x_Lt, Lt) x_Rt = min(x_Rt, Rt) if x_Lt <= Lt <= Rt <= x_Rt: self._add_line(line, i) elif x_Rt <= mid: Q.append((self._get_child(i, True), line, x_Lt, x_Rt)) elif mid < x_Lt: Q.append((self._get_child(i, False), line, x_Lt, x_Rt)) else: Q.append((self._get_child(i, True), line, x_Lt, mid)) Q.append((self._get_child(i, False), line, mid + 1, x_Rt)) def fold(self, x): #座標xの最小値を計算 i = 0 ans = 4 * 10 ** 18 while i != None: Lt, mid, Rt = self._S[i] c_Lt, c_Rt = self._C[i] if self._L[i] != None: ans = min(ans, self._f(self._L[i], x)) i = c_Lt if x <= mid else c_Rt return ans #Z-algorithm TとS[i:]のLCP判定は、T+'$'+S のようにSに出ない文字を挟んで実行するとよい #Reference: https://tjkendev.github.io/procon-library/python/string/z-algorithm.html def Z_algorithm(S): #SとS[i:]の最長共通接頭辞を求める N=len(S); A=[0]*N; i,j=1,0; A[0]=L=N while ik