The problem requires us to partition a sequence of data sizes into contiguous segments such that the sums of these segments are non-decreasing, and we need to minimize the total cost, which is the sum of squares of these segment sums.
To solve this problem efficiently, we can use a stack-based approach inspired by the Pool Adjacent Violators Algorithm (PAVA) used in isotonic regression. The key idea is to maintain the property that the average (or the sum) of each segment is less than or equal to the next one. Here's how we can apply this method:
Initialize: Start with an empty stack. Each data point is considered as a segment with a sum s_i and length l_i (initially 1).
Process Each Data Point:
Push a new segment onto the stack with sum s_i = a_i and length l_i = 1.
While the stack has at least two segments and the average of the previous segment is greater than the average of the current segment, merge the two segments:
Pop the current and previous segments.
Merge them into a new segment with sum s_new = s_prev + s_curr and length l_new = l_prev + l_curr.
Push the merged segment back onto the stack.
Compute the Total Cost:
After processing all data points, compute the sum for each segment in the stack.
The total cost is the sum of squares of these segment sums.
This method ensures that the sums of the segments are non-decreasing and tries to minimize the total cost by merging segments when necessary.
Here's how you can implement this approach in code:
n, type = map(int, input().split())
if type == 0:
a_list = list(map(int, input().split()))
else:
x, y, z, b1, b2, m = map(int, input().split())
b = [0]*n
b[0] = b1
b[1] = b2
for i in range(2, n):
b[i] = (x*b[i-1] + y*b[i-2] + z) % (1<<30)
p_list = []
l_list = []
r_list = []
for _ in range(m):
p, l, r = map(int, input().split())
p_list.append(p)
l_list.append(l)
r_list.append(r)
a_list = [0]*n
idx = 0
for i in range(n):
while i >= p_list[idx]:
idx += 1
a_list[i] = b[i] % (r_list[idx] - l_list[idx] +1) + l_list[idx]
stack = []
for a in a_list:
s_i = a
l_i = 1
stack.append([s_i, l_i])
while len(stack) >= 2 and stack[-2][0]/stack[-2][1] > stack[-1][0]/stack[-1][1]:
s1, l1 = stack.pop()
s0, l0 = stack.pop()
s_new = s0 + s1
l_new = l0 + l1
stack.append([s_new, l_new])
ans = 0
for s, l in stack:
ans += s*s
print(ans)
In this code:
We handle both types of inputs (type 0 and type 1) and generate the list a_list.
We then apply the stack-based merging algorithm.
Finally, we calculate the total cost by summing the squares of the segment sums.
This algorithm runs in O(n) time and should handle the large constraints specified in the problem.