You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.3 KiB

3 weeks ago
from typing import NamedTuple
class Piecewise_Constant(NamedTuple):
start: int
steps: list[tuple[int, int]]
def __rmul__(self, c):
return Piecewise_Constant(
self.start*c,
[(i, j*c) for i, j in self.steps]
)
def __neg__(self):
return (-1)*self
def __add__(self, a):
return Piecewise_Constant(
self.start+a,
[(i, j+a) for i, j in self.steps]
)
def add_conditional(self, fee):
return Piecewise_Constant(
self.start + fee if self.start else 0,
[(i, j+fee if j else 0) for i, j in self.steps]
)
# assumes contract size of $100
def conv_lim_pc(low, high):
s = 10000 if low is None else 0
t = []
if low is not None:
t.append((low, 10000))
if high is not None:
t.append((high + 1, 0))
return Piecewise_Constant(s, t)
def min_sum_pc(funcs):
sum = 0
evs = []
for f in funcs:
sum += f.start
last = f.start
for step in f.steps:
evs.append((step[0], step[1]-last))
last = step[1]
evs.sort()
i = 0
ans = sum
while i<len(evs):
o = evs[i][0]
while i<len(evs) and o==evs[i][0]:
sum += evs[i][1]
i+=1
ans = min(ans, sum)
return ans