We need to solve problem: given array a of length n (1 ≤ n ≤ 35000, ai ≤ n), and integer k (≤ min(n, 50)), we need to partition array into exactly k contiguous segments (each non-empty). For each segment, its value is the number of distinct numbers in that segment. The total value is sum of values of segments. We need to maximize total value.
We need to compute maximum sum of distinct counts over k contiguous partitions.
This is a classic DP optimization problem: DP[i][j] = maximum total value for first i elements partitioned into j segments. Transition: DP[i][j] = max_{t < i} ( DP[t][j-1] + distinct_count(t+1, i) ). We need to compute efficiently for n up to 35000, k up to 50.
We can optimize using divide and conquer DP optimization or segment tree with DP on distinct numbers. Since k is small (≤50) and n is moderate (35000), we can use DP with segment tree and maintain values while moving the right endpoint. This is similar to problems like "Array Partition into K subarrays maximizing sum of distinct numbers" or "Covering the array with segments to maximize sum of distinct numbers".
We need to compute for each j from 1 to k, DP[j][i] (or DP[i] for current j) using the previous DP[j-1]. For each j, we compute DP_cur[i] = max over t < i of (DP_prev[t] + distinct(t+1..i)). This is like we have a function f_i(t) = DP_prev[t] + distinct(t+1..i). As i increases, distinct(t+1..i) changes in a predictable way: when we move i to i+1, the distinct count for intervals ending at i+1 can be updated based on last occurrence of a_i+1. More precisely, for each left index t, distinct(t+1..i) is number of distinct elements in subarray from t+1 to i. When we add a new element at position i, the distinct count for intervals where the left index t is less than last occurrence of a_i (specifically, t+1 ≤ last_occurrence of a_i) remains same because a_i already present; for intervals with left index t+1 > last_occurrence, the distinct count increases by 1.
Thus, we can maintain a segment tree over t (possible cut positions) that stores DP_prev[t] + something that will be updated as i increases. For fixed j, we iterate i from 1 to n, and we want DP_cur[i] = max_{t=0..i-1} (DP_prev[t] + distinct(t+1,i)). Typically we let t range from 0 to i-1, where DP_prev[0] = 0 (meaning no elements before first cut). Also distinct(t+1,i) is number of distinct elements in segment starting at t+1 and ending at i. When i increments, we update the segment tree for all t in range [0, i-1] appropriately: for the new element a_i, let last = last occurrence of value a_i before i (or 0 if none). Then for all t such that t+1 > last? Actually distinct(t+1,i) includes a_i. The intervals that do not already contain a_i are those where the left index > last occurrence of a_i. Because if the left bound (t+1) is > last, then the segment [t+1, i] does not contain the previous occurrence of a_i, so a_i is new. If left bound ≤ last, then the segment already had a_i from previous occurrence, so distinct count does not increase.
So we can maintain a segment tree over t (from 0 to n) that initially (for i=0) holds DP_prev[t] (since distinct(t+1,0) is zero? Actually when i=0, there are no elements; but we will start i from 1). At step i, before computing DP_cur[i], we need the segment tree to represent values = DP_prev[t] + distinct(t+1, i). To do that, when we move to i, we update: for all t in [0, last_i - 1]? Let's be precise.
Define pos = last occurrence of a_i before i. If there is none, then pos = 0 (or we treat last occurrence index as 0). Then for all left boundaries L = t+1 such that L > pos, i.e., t >= pos, the distinct count increments by 1. Because if L = t+1 > pos, then the segment from L to i includes a_i, and since L > pos, it does not include the previous occurrence (if any) of a_i, so a_i is new. However, note: t ranges from 0 to i-1. For t >= pos, we want to add +1 to the value. But careful: when pos = 0, t >= 0 means all t from 0 to i-1 get +1. That's correct.
Thus, we can maintain a segment tree over t indices (0 to n) storing value = DP_prev[t] + current distinct(t+1, i). Initially for i=0, distinct(t+1,0) is 0 for all t? Actually for i=0 there are no elements, but we will start with i=1. We'll initialize segment tree with DP_prev[t] for all t (0..n) (DP_prev[n] might not be used). Then as we increase i from 1 to n, before querying for i, we perform an update: add +1 to range [pos, i-1]? Let's examine: we want for each t from 0 to i-1, the value = DP_prev[t] + distinct(t+1,i). At step i, after processing a_i, for t in [0, i-1], if t >= pos, then distinct(t+1,i) = distinct(t+1,i-1) + 1; else distinct(t+1,i) = distinct(t+1,i-1). Also for t = i? Not needed because t goes up to i-1. So we need to increment the segment tree values for t in [pos, i-1] by 1. But careful: The segment tree stores values for all t from 0 to n. At the beginning of step i (i.e., after processing i-1), we have values for t in [0, i-2] representing DP_prev[t] + distinct(t+1, i-1). For t = i-1, we might not have a value yet because previously distinct(t+1,i-1) would be for segment starting at i? Actually when we are at step i-1, the segment tree contained entries for t from 0 to i-2 (since those are the valid left indices for ending at i-1). At step i we need to include t = i-1 as a possible cut before element i? Because we can start a new segment at i, meaning t = i-1 (the segment from i to i). For t = i-1, distinct(i,i) is always 1 (the new element). But we need to have its base value DP_prev[i-1] plus distinct(i,i). However, before adding the new element, we haven't accounted for t = i-1. So at step i, we need to insert a new index t = i-1 into the segment tree. Its value initially should be DP_prev[i-1] + distinct(i,i) but distinct(i,i) = 1? But we must be careful about the incremental update process.
Standard approach: For each i from 1 to n, we first update the segment tree to reflect the new element a_i: range add +1 to all t with t >= last_occurrence[a_i] (but only up to i-1). Then we insert the t = i-1? Actually t = i-1 corresponds to starting segment at i. For t = i-1, the segment [i,i] includes a_i, so its distinct count is 1. However, after the range update for a_i, if we apply the range add +1 to [last, i-1] before inserting t = i-1, then t = i-1 would be included in that range if last <= i-1, which is always true because last < i. Then after we insert t = i-1 with some base, we would need to ensure it gets the +1 from the update if applicable. But the update happened before insertion, so we would miss adding +1 to t = i-1. So we need to order correctly.
Alternate common method: maintain segment tree over t from 0 to n, but we will process i from 1 to n. At start of step i, before processing a_i, the segment tree should represent values for all t in [0, i-1] of DP_prev[t] + distinct(t+1, i-1). To incorporate a_i, we need to:
- Add +1 to all t in [last_occurrence[a_i], i-1] (since those t have L=t+1 > last? Actually t >= last, because t is the index before the start. If t >= last, then L = t+1 >= last+1 > last, so indeed L > last). So range [last, i-1] gets +1.
- Then we need to consider t = i-1? But t = i-1 is already in the range [0,i-1]? At the moment before update, t = i-1 might not yet be in the segment tree because for i-1 we only had t up to i-2 when we ended previous step. However, we can include t = i-1 initially as having value DP_prev[i-1] + distinct(i,i-1)?? That's zero because segment [i, i-1] empty. But then after the update, we add +1 to range [last, i-1], which includes t = i-1, so the value becomes DP_prev[i-1] + 1, which is correct for segment starting at i and ending at i. So we need to first add the element t = i-1 with base value DP_prev[i-1] (since distinct(i, i-1)=0). Then do the range update +1 to [last, i-1]. That yields DP_prev[i-1] + 1. Good.
But we also need to consider t = i? No.
Thus steps for each i:
- Insert index t = i-1 into segment tree, setting its value to DP_prev[i-1] (initial distinct count 0).
- Then update: add +1 to range [last_occurrence[a_i], i-1] (where last_occurrence[a_i] is the previous index of a_i; if none, last=0).
- Then query the maximum over t in [0, i-1] to get DP_cur[i] = max(DP_prev[t] + distinct(t+1,i)). That's the value.
Edge: At i=1: before processing, segment tree is empty (or contains t=0?). We need base DP_prev[0] = 0. So we can initially have t=0 inserted with value DP_prev[0]=0. For i=1:
- Insert t = i-1 = 0? But t=0 already inserted. So careful: we might handle t=0 separately. Let's just initialize segment tree with t=0 value = DP_prev[0] = 0 before loop. Then for i from 1 to n:
- If i>1, insert t = i-1 with base = DP_prev[i-1]. (Because for i=1, i-1=0 already present; we don't insert again.)
- Then update: add +1 to range [last[a_i], i-1] (where last[a_i] is previous occurrence position, initially 0).
- Then query max over t in [0, i-1] to get DP_cur[i].
But note: For i=1, after inserting t=0 (already there), update range [last[a1], 0] => if last[a1] is 0? For first occurrence, last=0, range [0,0] gets +1, making value at t=0 become DP_prev[0] + 1 = 1. Then query max over [0,0] gives 1, which is distinct count for segment [1,1] = 1, correct.
Now we need to consider DP_prev[t] for t up to n. We'll compute DP_cur for all i. At the end of processing each j, we have DP_cur[1..n] for current number of segments. Then we set DP_prev = DP_cur for next j. But careful: DP_cur[i] is the maximum total value for first i elements partitioned into j segments. For j=1, DP_cur[i] is just distinct count from 1 to i? Actually it's max over t? For j=1 we have exactly 1 segment covering first i elements. So DP_cur[i] = distinct(1,i). Our DP recurrence: DP[i][1] = distinct(1,i). That's consistent with the above method: with DP_prev[t] being DP[0][0]? Let's define base: For j=0, DP[0][0] = 0 for no elements, and DP[i][0] = -inf for i>0. But we typically start with j=1, and we need DP_prev[t] for t from 0 to i-1 where DP_prev[t] corresponds to DP[t][j-1] for exactly j-1 segments covering first t elements. So for j=1, DP_prev[t] is DP[t][0] which is 0 when t=0 and -inf for t>0 (since we cannot cover non-zero elements with 0 segments). So we must set DP_prev[t] to -inf for t>0 initially. Then the algorithm above with segment tree will compute DP_cur[i] correctly: only t=0 is viable. So we need to initialize DP_prev array appropriately.
Thus for each j (1..k):
- Initialize segment tree (size n+1) with -inf for all positions, but we will set values as we go? Actually we want to dynamically add t as we process i. The segment tree must support point assignment (set value at index t) and range add (increment by value) and range max query. Since we need to insert t gradually (from 0 to n-1) as i increases, we can just build a segment tree over indices 0..n with initial values -inf. At the start of processing j, we set t=0 to DP_prev[0] (which should be 0 for j=1? Actually DP_prev[0] = 0 for all j? Because covering zero elements with 0 segments gives 0. For j>1, DP_prev[0] = -inf? Wait: When we compute DP[i][j] for j segments, we need DP[t][j-1] where t can be 0 only if j-1=0? In general, DP[t][j-1] is defined only for exactly j-1 segments covering t elements. If j-1 > 0, then t must be at least j-1 because each segment has at least one element. So DP[0][j-1] for j-1>0 is impossible ( -inf). So we must set DP_prev[t] appropriately based on j-1.
Thus, before processing j, we have DP_prev array of length n (0..n) where DP_prev[t] is DP[t][j-1] (maximum value for first t elements with j-1 segments). For t < j-1, DP_prev[t] = -inf (impossible). For t >= j-1, it's computed.
In the algorithm, for each i we need to consider t from j-1? Actually the cut positions t must satisfy that we can partition first t elements into j-1 segments, meaning t >= j-1. Also t can be 0 only if j-1=0. So the valid t range is from j-1 to i-1? But we can simply keep DP_prev[t] as -inf for invalid t, and then the max query will automatically ignore them.
Now the dynamic segment tree approach: for each i from 1 to n:
- If i-1 >= j-1? Actually we only add t = i-1 if DP_prev[i-1] is not -inf? But we can add it anyway; its value will be -inf, then updates won't matter. However, after updates, it might become something else? But -inf + something is still -inf if we treat -inf carefully: we need to handle that we should not allow -inf + addition to become finite. So we can store -inf as a very small number (e.g., -1e9) and ensure that addition does not produce finite values from -inf. Actually if we do range add, all indices get added, including those with -inf. That would erroneously bring them up. So we must only update and add to positions that are "active" (i.e., have valid DP_prev). A common trick: maintain segment tree with two operations: point assignment (set value) and range add. For each t we assign its value initially as DP_prev[t] (which might be -inf). Then we do range adds only over intervals, but if the base is -inf, after adding it becomes -inf+something, which is not valid. To avoid, we can treat -inf as -10^9 and ensure that after additions it remains below any feasible maximum, but then max query might still consider it if it becomes higher? Actually -inf + 1e5 is still negative large, but if the real max is positive, it's fine. However, DP values are at most n (max distinct per segment) and total sum up to nk? Actually max total value is at most n (since each element can contribute at most 1 distinct per segment? But across k segments the sum of distinct counts can exceed n because same element can count in multiple segments? Actually each segment counts distinct numbers within that segment. So an element can contribute to distinct count in each segment that contains it, but it may be counted multiple times. Maximum total could be up to kn? But n ≤ 35000, k ≤ 50, so maximum sum could be up to 1.75e6. But that's still manageable. But -inf should be less than -1e9 to be safe. So we can set -inf = -1e9 (or -1e15) and then range adds of at most n (35000) will still keep it negative, but if we add many times over many steps? Actually each i step we do a range add, and the segment tree stores accumulated adds for each node. For positions with base -inf, after many adds (over many i's) they could become large positive if we keep adding. But note that for a given j, we process i from 1 to n. For each i, we add +1 to range [last[a_i], i-1]. Over the whole loop, each position t (which corresponds to left cut) will receive multiple increments: for each i where t+1 > last[a_i] meaning a_i is new for that left, it gets +1. So total increments over the whole run for a given t could be up to n - t (the length of segment). That's up to 35000. If base is -inf = -1e9, after adding up to 35000, it would be about -965000, still negative. So it won't become positive and won't affect max. However, if we set -inf = -1e9, and the real DP values are up to 1.75e6, then -965k could be less than real max, but still could be larger than real max? Real max is positive up to 1.75e6, so -965k is smaller, so no issue. But we must ensure -inf plus additions never exceed the actual possible maximum. Since additions are at most 35000, if we set -inf = -1e9, it's safe. But to be precise, we could use -1e15.
Alternative approach: maintain segment tree with lazy propagation and store max. For positions that are invalid, we could set their value to -inf and not apply range adds to them? But lazy adds apply uniformly to the whole segment. If a segment contains both valid and invalid positions, the max for that segment after adding might come from an invalid position if it becomes higher than valid ones after addition? But since invalid positions are at -inf plus some additions, they remain much lower than valid ones if we set -inf low enough. However, there is a subtlety: suppose we have a valid position with value V, and an invalid one with base -inf = -1e9. After many increments (say 1e6), invalid becomes -9e8, still less than V if V is positive. But if V is also negative? V is non-negative (DP sum is non-negative because distinct counts are positive). So it's fine.
But careful: For j=2 onward, DP_prev[t] for small t (like t=0) might be -inf. So we can set DP_prev[0] to 0 only for j=1? Actually DP[t][j-1] for t=0 should be 0 if j-1=0, else -inf. So we set DP_prev accordingly.
Thus we can initialize segment tree for each j as: build an array init of size n+1 with -inf. Then set init[0] = DP_prev[0] (which is 0 if j-1=0 else -inf). But we will be adding t = i-1 as we go; we could also pre-initialize all positions with DP_prev[t] and then use a pointer to enable positions as we go? Actually we need to ensure that when we do range updates, we only affect positions t that are "active" up to i-1. Because if we have positions t that are > i-1, they should not be considered. So we need to restrict query and updates to range [0, i-1]. However, if we pre-initialize all t with DP_prev[t] and then for each i, we update range [last, i-1] and query [0, i-1], but the positions t > i-1 have values that could be updated erroneously if our range update includes them? Actually our range update is specifically [last, i-1], which only goes up to i-1. So positions t > i-1 are not touched. So if we pre-assign all t with DP_prev[t], and then for each i from 1 to n, we apply the range update and query, we must also ensure that we do not consider t that are > i-1. In the query we restrict to [0, i-1]. That works. Also we need to ensure that for t = i-1, its base DP_prev[i-1] is included from start. But we also need to reflect that distinct(t+1,i) for t = i-1 is 1, but our range update will add +1 to that position (since last ≤ i-1). However, what about the effect of previous updates? When we process i, we need to apply the update for a_i which adds +1 to [last, i-1]. But also we need to have applied all previous updates for earlier elements to correctly have the distinct count for intervals ending at i. If we pre-initialized all t with DP_prev[t] and then for each i we apply the range update for a_i (and only that update) and then query, will that yield DP_cur[i]? Let's test.
Goal: after processing i, the segment tree value for each t should be DP_prev[t] + distinct(t+1,i). This distinct count is the number of distinct elements in a[t+1..i]. This can be built incrementally by processing each new element. If we start with i=0: all values = DP_prev[t] + 0 (since no elements). Then for each i from 1 to n, we apply update: for t in [0, i-1] (or more precisely, t from last to i-1) add +1. This incremental process yields correct values. If we pre-initialize the tree with DP_prev[t] (which is DP_prev[t] + 0 for i=0), then for i=1 we apply update for a1 to range [last,0] (last=0) add +1, giving DP_prev[t] + distinct(t+1,1). Then query. For i=2, we apply update for a2 to range [last_a2, 1] add +1, which updates values to DP_prev[t] + distinct(t+1,2). This works because updates are cumulative. So we don't need to insert t gradually; we can have all t already in the tree. However, we must ensure that for t >= i, those positions should not be considered because distinct(t+1,i) is defined only if t < i (i.e., segment starts at t+1 ≤ i). But if we have pre-initialized all t, the values for t >= i will be DP_prev[t] plus some updates from elements? They would have received updates for indices i where t < i? Actually for a given t, when we process i, we only update range [last, i-1]. So if t >= i, then t is not in that range because the range ends at i-1. So t does not get updated at step i. So at step i, for t >= i, the value remains DP_prev[t] + sum of updates from steps where i' ≤ t? Wait, we need to see: The value for t at step i should reflect distinct(t+1,i). If t >= i, then t+1 > i, so the segment is empty or invalid. But we should not include those t in our query. If we keep them in the tree, they will have some value from previous updates (when i was larger than t?) Actually consider t = 5. When i=3, t=5 is >= 3, we do not want to consider it. At step i=3, updates only affect t <= i-1 =2. So t=5 is unchanged from initial DP_prev[5]. But later when i becomes 6, at step i=6, we will update range up to 5, so t=5 gets updates for elements from when it became less than i. So indeed, for t >= i, the value is just DP_prev[t] (plus maybe some updates from earlier steps? No, because earlier steps i' had i' <= t, and for i' where t >= i', t is not in [last, i'-1] because i'-1 <= t-1? Actually if i' <= t, then i'-1 <= t-1, so t might be > i'-1, so it's not in the range. So t only gets updates when i > t, because the update range is up to i-1. So when i <= t, no updates. So the value for t at step i is DP_prev[t] if i <= t, and DP_prev[t] + sum of updates for steps i' where i' > t? Actually when i becomes larger than t, then t gets updates for each i' > t. So for step i, if i > t, then t has received updates for all i' from t+1 up to i. That yields distinct(t+1,i). Good. So if we keep all t in the tree, the value for t at step i is exactly DP_prev[t] + distinct(t+1,i) when i > t, and for i <= t it's DP_prev[t] (which we don't query). So it's consistent. Therefore we can simply build the segment tree once for each j with initial values DP_prev[t] for all t from 0 to n (with DP_prev[t] = -inf for invalid t). Then we iterate i = 1..n:
- Update: add +1 to range [last[a_i], i-1] (where last[a_i] is the previous occurrence index of value a_i; we need to map last occurrence of each value as we go).
- Then DP_cur[i] = query max over range [0, i-1] (or more precisely over t from 0 to i-1). But note that we must ensure we only consider t that are at least j-1? That's automatically handled because DP_prev[t] is -inf for t < j-1, so their values after updates remain -inf+some (still negative large) and won't be max.
- After computing DP_cur[i], we continue.
But careful: At step i, before the update for a_i, the tree should reflect distinct(t+1,i-1). However, we are applying the update for a_i first, then querying. That gives distinct(t+1,i). So DP_cur[i] = max_{t < i} (DP_prev[t] + distinct(t+1,i)). Yes. That's correct. The order: update then query. But we need to make sure that the update range includes t = i-1? When i-1 is in range [last, i-1], it gets +1. But what about the base value for t = i-1? It is DP_prev[i-1] which is set initially. Good. So after update, t = i-1 has DP_prev[i-1] + 1 = DP_prev[i-1] + distinct(i,i). So it's fine.
Thus we don't need to insert gradually; we can initialize the segment tree with all DP_prev[t] (including t up to n) and then process.
One nuance: For j=1, DP_prev[t] is DP[t][0]. For t=0, DP[0][0]=0. For t>0, DP[t][0] = -inf. So we set initial array accordingly.
Now after we compute DP_cur for all i, that becomes DP_prev for next j.
Complexity: O(k * n log n) because for each i we do one range update and one range query (both O(log n)). n=35000, k up to 50 => 1.75e6 operations, each log n ~ 15, so about 26 million, feasible.
We need to be careful with indices: last occurrence array of size up to n (values up to n). We'll maintain last[val] as last index where val appeared, initially 0 (since 0 is before first element). We'll update after processing i (or before?). At step i, we need last[a_i] to be the previous occurrence index. So we can use current last[a_i] (which is the index of previous occurrence, 0 if none). Then after we use it, we set last[a_i] = i for next occurrences.
Thus algorithm summary:
Input n, k, array a[1..n].
Initialize dp_prev array of length n+1 (0-indexed) with -INF.
dp_prev[0] = 0. (This is for j=0? Actually for first iteration j=1, dp_prev corresponds to j-1=0 segments. So dp_prev[0]=0, others -INF.)
For j = 1 to k:
Build segment tree over indices 0..n with initial values dp_prev[0..n].
Reset last occurrence array: size n+1, filled with 0.
Initialize dp_cur array of length n+1 with -INF (dp_cur[0] maybe not used but we only need up to n).
For i from 1 to n:
// range update: add 1 to indices [last[a[i]], i-1]
L = last[a[i]]
R = i-1
if L <= R: segment_tree.range_add(L, R, 1)
// query max over indices [0, i-1] to get dp_cur[i]
dp_cur[i] = segment_tree.range_max(0, i-1)
// update last occurrence
last[a[i]] = i
// After loop, dp_cur holds DP for j segments.
// Prepare for next iteration: dp_prev = dp_cur.
After finishing all k iterations, answer is dp_prev[n] (since we need exactly k segments covering all n cakes). Because after last j=k, dp_cur[n] is max total value for first n elements with k segments. Print it.
We need to verify with examples.
Example 1: n=4, k=1, a=[1,2,2,1].
j=1: dp_prev initially: [0, -inf, -inf, -inf, -inf].
Build segment tree.
last all 0.
i=1: L=last[1]=0, R=0 => range add [0,0] +1. Tree now: index0: 0+1=1. Query max [0,0] => 1 => dp_cur[1]=1.
last[1]=1.
i=2: L=last[2]=0, R=1 => add [0,1] +1. Before update, tree values: index0:1 (from previous), index1:-inf. After adding: index0 becomes 2, index1 becomes -inf+1? Actually index1 was -inf; after +1 becomes -inf+1 (still effectively -inf if we use large negative). But careful: if we use -inf = -1e9, adding 1 gives -999999999, still very negative. So query max [0,1] => max(2, -inf) = 2 => dp_cur[2]=2. last[2]=2.
i=3: L=last[2]=2, R=2 => add [2,2] +1. index2 initially -inf, after +1 still -inf. Query max [0,2] => max(index0,index1,index2). index0? It had previous updates: initially 0, then i=1 added +1 =>1, i=2 added +1 =>2, i=3? No addition to index0 because L=2, range [2,2] only. So index0 still 2. index1: initially -inf, i=2 added +1 => -inf+1, still negative large. index2: -inf+1. So max = 2 => dp_cur[3]=2. last[2]=3.
i=4: L=last[1]=1, R=3 => add [1,3] +1. After add: index0 unchanged (2). index1: -inf+1+1? Actually index1 had maybe -inf+1 from i=2? Now +1 => -inf+2. Still negative. index2: -inf+1 from i=3, now +1 => -inf+2. index3: initially -inf, now +1 => -inf+1. So max remains 2? Wait, but distinct(1,4) = distinct {1,2,2,1}=2, so dp_cur[4] should be 2. Yes, 2. So answer =2. Correct.
Example 2: n=7, k=2, a=[1,3,3,1,4,4,4].
We need to compute j=1 then j=2.
j=1: compute dp_cur for one segment: essentially distinct(1..i). Let's compute: dp1[1]=1, dp1[2]=2 (1,3), dp1[3]=2 (1,3,3), dp1[4]=2? distinct(1..4)= {1,3}=2, dp1[5]=3 (1,3,4), dp1[6]=3, dp1[7]=3. So dp1 = [0? Actually dp1[0] not used; dp1[1]=1, dp1[2]=2, dp1[3]=2, dp1[4]=2, dp1[5]=3, dp1[6]=3, dp1[7]=3]. That's for one segment covering first i elements.
Now j=2: dp_prev = dp1 (but we need dp_prev[0]=0? Actually for j=2, dp_prev[t] should be DP[t][1] (max with 1 segment for first t). That includes t=0? DP[0][1] = -inf because can't cover 0 elements with 1 segment. But our dp1 array currently has dp1[0] undefined. We need to set dp_prev[0] appropriately. For j=2 (j-1=1), the base is DP[t][1] for t from 0..n. DP[0][1] is impossible, so dp_prev[0] should be -inf. But we previously had dp1[0]? Not computed. So we must be careful with the dp_prev array initialization for each j.
When moving from j-1 to j, we need to have DP[t][j-1] for all t. For j-1 >= 1, DP[0][j-1] is -inf. Also DP[t][j-1] for t < j-1 are -inf because need at least j-1 elements for j-1 segments. So we must set those to -inf.
In the first iteration (j=1), we used dp_prev[0]=0, others -inf. That matched j-1=0.
Now for j=2, we need to set dp_prev = dp_cur from previous iteration, but we also need to modify dp_prev[0] to -inf because now j-1=1. So we can't just copy dp_cur; we need to define dp_prev array appropriately. dp_cur from previous iteration gave DP[i][1] for i=0? Actually we computed dp_cur[i] for i from 1 to n. We didn't compute dp_cur[0]. So we should also compute dp_cur[0]? But DP[0][j] is only defined for j=0 (0). For j>=1, DP[0][j] = -inf. So when we finish j=1, we have DP[0][1] should be -inf. So we should set dp_cur[0] = -inf for j=1 (since covering zero cakes with one segment is impossible). But we didn't include that. However, our DP recurrence for j=1 used dp_prev[0] = 0 because we considered exactly one segment covering all elements from 1 to i; we never used dp_cur[0]. So it's fine if we set dp_prev[0] manually for each j. In the next iteration, we should set dp_prev[0] = -inf because we cannot start with 0 segments? Actually we need DP[t][j-1] with j-1=1. So dp_prev[0] should be -inf. So we need to set the dp_prev array accordingly before building segment tree for each j.
Thus after computing dp_cur for j segments, we should define for next iteration: dp_prev = array of size n+1 where for t=0, dp_prev[0] = -inf (if next j-1>0) else 0? But we can just compute dp_cur for all t from 0 to n. We can compute dp_cur[0] as -inf for j>=1, and dp_cur[0]=0 for j=0. But we are not storing j=0 explicitly. We'll handle as:
Initialize prev_dp array of length n+1 with -INF. Set prev_dp[0] = 0. (This corresponds to j=0)
For j in 1..k:
// Compute cur_dp using prev_dp as DP[t][j-1]
Build segment tree with initial values prev_dp[0..n]
Process i=1..n as described to compute cur_dp[i]
After loop, set cur_dp[0] = -INF (since covering 0 elements with j segments impossible for j>=1)
Then set prev_dp = cur_dp for next iteration.
But is cur_dp[0] needed for next iteration? For j+1, prev_dp[0] should be -INF. So setting cur_dp[0] to -INF is correct.
Check example 2:
Initialize prev_dp: index0=0, others -inf.
j=1: compute cur_dp[1..7] as above. Then cur_dp[0] = -inf. So after j=1, prev_dp becomes cur_dp: prev_dp[0] = -inf, prev_dp[1]=1, prev_dp[2]=2, prev_dp[3]=2, prev_dp[4]=2, prev_dp[5]=3, prev_dp[6]=3, prev_dp[7]=3.
Now j=2: Build segment tree with prev_dp. Process i=1..7.
We need to verify that we get correct answer 5.
Let's simulate manually with algorithm.
We have a: 1 3 3 1 4 4 4.
Initialize last all 0.
Segment tree initially values: index0:-inf, idx1:1, idx2:2, idx3:2, idx4:2, idx5:3, idx6:3, idx7:3 (others -inf). We'll track values as we process.
i=1:
L = last[1] = 0, R = 0. Add +1 to [0,0].
After add: index0: -inf+1 = -inf+1 (still large negative). Others unchanged.
Query max over [0,0]: only index0, value = -inf+1. That's effectively -inf. But we need dp_cur[1] for j=2? However, can we have 2 segments covering first 1 element? No, because each segment at least one cake, so 2 segments need at least 2 elements. So dp_cur[1] should be -inf. So that's correct: -inf.
last[1] = 1.
i=2:
L = last[3] = 0 (first occurrence), R = 1.
Add +1 to [0,1].
Before update, values: index0: -inf+1? Actually after i=1, index0 had been incremented by +1, so it's -inf+1. index1: 1.
After adding +1 to [0,1]: index0 becomes -inf+2; index1 becomes 2.
Now query max over [0,1]: max(index0 (still -inf), index1=2) => 2.
So dp_cur[2] = 2. Indeed partition: [1][3] gives values 1+1=2? Wait, for 2 segments covering first 2 elements, we can have [1] and [3], distinct each 1, total 2. Yes.
last[3] = 2.
i=3:
L = last[3] = 2, R = 2.
Add +1 to [2,2].
Before update: index2=2.
After: index2 becomes 3.
Query max over [0,2]: values: index0:-inf, index1=2, index2=3 => max=3.
So dp_cur[3] = 3. Check: partitions of first 3 elements into 2 segments: possibilities: [1,3] [3] => distinct first segment: {1,3}=2, second: {3}=1 total 3. Or [1] [3,3] => 1+1=2. So max=3. Good.
last[3] = 3.
i=4:
L = last[1] = 1, R = 3.
Add +1 to [1,3].
Before update: index1=2, index2=3, index3=2 (prev_dp[3]=2). Actually we need to check values: we have initial prev_dp: index3=2. So at i=3 we had index3=2? But we added updates up to i=3. Let's recalc all values systematically.
Better to track incremental values. Let's construct a table of values for each t after each update.
Initial after building tree: values = prev_dp = [ -inf, 1, 2, 2, 2, 3, 3, 3, ... ]
Now i=1:
Add +1 to [0,0]: new values: index0: -inf+1 (still -inf), others unchanged.
Query [0,0] -> -inf => dp_cur[1] = -inf.
Then last[1]=1.
i=2:
Before i=2, values: index0: -inf+1, index1:1, index2:2, index3:2, index4:2, index5:3, index6:3, index7:3.
Add +1 to [0,1]:
index0: -inf+1 +1 = -inf+2
index1: 1+1=2
So values become: index0:-inf+2, index1:2, others unchanged.
Query [0,1] -> max(2, -inf+2) = 2 => dp_cur[2]=2.
last[3]=2.
i=3:
Before: values as above.
Add +1 to [2,2]:
index2: 2+1=3.
So values: index0:-inf+2, index1:2, index2:3, index3:2, index4:2, index5:3, etc.
Query [0,2] -> max(2,3) = 3 => dp_cur[3]=3.
last[3]=3.
i=4:
Before: values: index0:-inf+2, index1:2, index2:3, index3:2, index4:2, index5:3, index6:3, index7:3.
Add +1 to [1,3]:
index1: 2+1=3
index2: 3+1=4
index3: 2+1=3
So after: index0:-inf+2, index1:3, index2:4, index3:3, others unchanged.
Query [0,3] -> max(index1=3, index2=4, index3=3, index0 negative) = 4 => dp_cur[4]=4.
Check: partitions of first 4 into 2 segments: possibilities:
[1][3,3,1] => 1 + distinct(2..4)= {3,1}=2 total 3.
[1,3][3,1] => distinct(1..2)={1,3}=2 + distinct(3..4)={3,1}=2 total 4.
[1,3,3][1] => distinct(1..3)={1,3}=2 + 1 = 3.
[1][3][1] not allowed because need exactly 2 segments.
So max=4, correct.
last[1]=4.
i=5:
Before: values: index0:-inf+2, index1:3, index2:4, index3:3, index4:2, index5:3, index6:3, index7:3.
L = last[4] = 0 (first occurrence of 4), R = 4.
Add +1 to [0,4]:
index0: -inf+2+1 = -inf+3
index1: 3+1=4
index2: 4+1=5
index3: 3+1=4
index4: 2+1=3
After: index0:-inf+3, index1:4, index2:5, index3:4, index4:3, others unchanged.
Query [0,4] -> max of indices 0..4: max(4,5,4,3) = 5 => dp_cur[5]=5.
Check: partition of first 5 into 2 segments: possibilities:
[1,3,3,1][4] => distinct(1..4)=2 + 1=3
[1,3,3][1,4] => distinct(1..3)=2 + distinct(4..5)={1,4}=2 =>4
[1,3][3,1,4] => 2 + distinct(3..5)={3,1,4}=3 =>5
[1][3,3,1,4] => 1+3=4? distinct(2..5)={3,1,4}=3 =>4?
So max=5. Good.
last[4]=5.
i=6:
Before: values after i=5: we have index0:-inf+3, index1:4, index2:5, index3:4, index4:3, index5:3, index6:3, index7:3.
L = last[4] = 5, R = 5.
Add +1 to [5,5]:
index5: 3+1=4
After: index5=4.
Query [0,5] -> max among indices 0..5: values: index1=4, index2=5, index3=4, index4=3, index5=4 => max=5 => dp_cur[6]=5.
Check: first 6 elements: possible optimal? [1,3][3,1,4,4] => 2 + distinct(3..6)={3,1,4}=3 =>5. Or [1,3,3,1][4,4] =>2+1=3, etc. So 5.
last[4]=6.
i=7:
Before: values: index0:-inf+3, index1=4, index2=5, index3=4, index4=3, index5=4, index6=3, index7=3.
L = last[4] = 6, R = 6.
Add +1 to [6,6]:
index6: 3+1=4
After: index6=4.
Query [0,6] -> max among 0..6: still max=5 (index2=5). So dp_cur[7]=5.
last[4]=7.
End. So dp_cur[7]=5, which matches answer.
Thus algorithm works.
Example 3: n=8, k=3, a=[7,7,8,7,7,8,1,7]. Answer 6. We can test quickly.
Now we need to implement segment tree with lazy propagation for range add and range max query.
Implementation details:
- n up to 35000, k up to 50.
- Use 1-indexed for array a? We'll use 0-indexed for internal? Simpler: Use 0-index for DP indices 0..n.
- a[i] for i=1..n.
- INF = 1e9 (or 1e15). Since max positive value maybe up to n*k <= 1.75e6, we can set INF = 1e9, NEG_INF = -1e9 (but we need more negative to avoid overflow to positive after many adds? The maximum adds a single index can receive is at most n (since each step it can get at most +1, and there are n steps). So if we set NEG_INF = -1e9, after up to 35000 adds, it becomes at most -965000, still negative. That's fine. But if we set NEG_INF = -1e9, then after range adds of +1, it will increase; but there might be indices that start as -inf and get up to -inf + n. Since n is 35000, still far less than possible positive values (which are up to about 1.75e6). So the max query will not pick those. However, consider a scenario where all DP_prev are -inf except some; the max will be from valid ones. So we are safe.
But we need to be careful with overflow when adding to -inf: if we use int, -1e9 + 35000 = -965000, still safe. But we might have multiple j iterations? For j>1, DP_prev values themselves are up to positive 1.75e6, and -inf is set to something like -1e9, still far below. So okay.
Alternatively, we could use long long for safety.
Simplify: Use long long, set NEG_INF = -1e18, and add freely.
Segment tree: size = n+1 (0..n). Build initial array init of length n+1. Each node stores max value in segment and lazy add. Standard.
Pseudo:
struct SegTree {
int n;
vector tree, lazy;
void build(vector& arr, int node, int l, int r) {
if(l == r) { tree[node] = arr[l]; return; }
int mid = (l+r)/2;
build(arr, node2, l, mid);
build(arr, node2+1, mid+1, r);
tree[node] = max(tree[node2], tree[node2+1]);
}
SegTree(vector& arr) {
n = arr.size()-1; // if arr indexed 0..n
tree.resize(4*(n+1));
lazy.assign(4*(n+1), 0);
build(arr, 1, 0, n);
}
void push(int node) {
if(lazy[node]) {
tree[node2] += lazy[node];
lazy[node2] += lazy[node];
tree[node2+1] += lazy[node];
lazy[node2+1] += lazy[node];
lazy[node] = 0;
}
}
void range_add(int node, int l, int r, int ql, int qr, long long val) {
if(ql > r || qr < l) return;
if(ql <= l && r <= qr) {
tree[node] += val;
lazy[node] += val;
return;
}
push(node);
int mid = (l+r)/2;
range_add(node2, l, mid, ql, qr, val);
range_add(node2+1, mid+1, r, ql, qr, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
long long range_max(int node, int l, int r, int ql, int qr) {
if(ql > r || qr < l) return NEG_INF;
if(ql <= l && r <= qr) return tree[node];
push(node);
int mid = (l+r)/2;
return max(range_max(node2, l, mid, ql, qr), range_max(node2+1, mid+1, r, ql, qr));
}
};
But we need to careful about indices: arr length n+1 (0..n). So segment tree size n (which is n). We'll pass n as the max index.
Alternatively, we can implement iterative segment tree with lazy? Might be simpler with recursive given constraints.
Now DP loops:
vector prev_dp(n+1, NEG_INF);
prev_dp[0] = 0;
for (int j = 1; j <= k; ++j) {
// Build segment tree with prev_dp
SegTree st(prev_dp); // expects vector size n+1
vector cur_dp(n+1, NEG_INF);
vector last(n+1, 0); // value range up to n
for (int i = 1; i <= n; ++i) {
int val = a[i];
int L = last[val];
int R = i-1;
if (L <= R) {
st.range_add(1, 0, n, L, R, 1);
}
cur_dp[i] = st.range_max(1, 0, n, 0, i-1);
last[val] = i;
}
// After loop, set cur_dp[0] = NEG_INF for j>=1 (but already NEG_INF because initialized; but maybe we need to explicitly set)
prev_dp = cur_dp;
}
cout << prev_dp[n] << endl;
But we must ensure that for j=1, prev_dp[0] was 0, but cur_dp[0] remains NEG_INF, which is correct for j=2. So fine.
However, there is subtle point: In j=1, when we query for i, we only consider t in [0,i-1] with prev_dp[t] possibly -inf except t=0. But our segment tree initially has prev_dp[0]=0 and others -inf. After updates, they become as needed. So correct.
Now complexity O(k * n log n) with n=35000, k=50, ~ 5035000log2(35000) ≈ 503500016 = 28 million, fine.
Now we need to confirm that the DP recurrence indeed yields the maximum sum of distinct counts. Yes, because we are taking max over partitions.
Edge Cases:
- k = n: each segment is exactly one element. Then total value = n (since each element distinct count 1). Our DP should produce that. Let's test: n=3,k=3, array any. j=1: prev_dp after j=1: dp1[i] = distinct(1..i) (max with 1 segment). But for j=2 and j=3 we need to compute. Eventually should get n. Could test quickly: n=3, a=[1,1,1], k=3 -> each box one cake, each value=1, total=3. Our DP: j=1: dp1[1]=1, dp1[2]=1, dp1[3]=1. j=2: compute as above. Let's simulate manually: dp_prev (j=1) values: [ -inf, 1,1,1]? Actually dp_prev[0] = -inf for j=2? Wait before j=2, prev_dp after j=1 we set cur_dp[0] = -inf, so prev_dp = [ -inf, 1,1,1]. Now for j=2, process:
i=1: update? L=0,R=0 add +1 -> index0: -inf+1, query [0,0] => -inf -> cur[1] = -inf.
i=2: L=last[a2] =? a2=1, last after i=1 set to 1. So L=1, R=1, add +1 to [1,1] -> index1: 1+1=2. Query [0,1] -> max(index0 negative, index1=2) => 2 -> cur[2]=2.
i=3: L=last[1]=2, R=2 add +1 -> index2: 1+1=2. Query [0,2] -> max(index1=2? Actually after i=2, index1=2; after i=3 update, index2 becomes 2; index0 negative; query gives 2? But we need cur[3]? For 2 segments covering 3 elements, max is 2? Actually partitions: [1][1][?] need exactly 2 segments: either [1,1][1] -> distinct first=1, second=1 total=2; or [1][1,1] -> 1+1=2. So cur[3]=2. Good.
So after j=2, cur = [ -inf, -inf, 2, 2]? Actually cur[1] = -inf, cur[2]=2, cur[3]=2.
Now j=3: prev_dp = [ -inf, -inf, 2, 2]. Process:
i=1: L=0,R=0 add +1 -> index0:-inf+1; query [0,0] => -inf => cur[1] = -inf.
i=2: L=last[a2]=0? a2=1, last initially 0, so L=0,R=1 add +1 -> index0:-inf+2, index1:-inf? Actually index1 is -inf, plus 1 = -inf+1?; query [0,1] => max(negative, negative) = some negative? But we need cur[2]? For 3 segments covering 2 elements impossible, so -inf. That's fine.
i=3: L=last[a3]? after i=2, last[1]=2. So L=2,R=2 add +1 -> index2: 2+1=3. Query [0,2] -> max(index2=3, index0,index1 negative) => 3. So cur[3]=3. Perfect.
Thus answer =3.
So algorithm works.
Now we need to ensure we handle large n and k efficiently. The segment tree of size n+1 ~ 35001, recursion depth log2(35000) ~ 16, safe.
Potential pitfalls: The range update [L, R] may have L > R (if last occurrence is after i-1? That can't happen because last < i always, so L = last <= i-1, so R = i-1 >= L. But if last = i? No, last is previous occurrence index, always < i. So L <= i-1, so L <= R. So update always non-empty? Actually if i=1, L=0,R=0 okay. If last = i-1, then L = i-1, R = i-1, still non-empty.
But we should still check condition if L <= R.
Now about memory: For each j we build a new segment tree. We can reuse by resetting but building new is fine: O(n) each time, total O(k*n) memory allocation but okay.
Alternatively we could use a Fenwick tree? But range add and range max query not directly supported by Fenwick; we need segment tree with lazy.
Implementation details in C++: We'll use long long, define INF as something like 1e15, NEG_INF as -1e15.
But careful: When we add to -INF, it might overflow if INF is too big? Use long long.
Set NEG_INF = -1e15.
Now confirm maximum positive: max distinct per segment ≤ n, total sum ≤ kn ≤ 5035000 = 1,750,000. So 1e15 is safe.
Now we need to ensure we don't have any off-by-one in segment tree indices. We'll store array arr of size n+1, index from 0 to n. Build with l=0, r=n.
In the loops, for i from 1 to n, we query [0, i-1]. That includes index 0..i-1. Good.
Now we also need to update range [L, R]. L is last[val] which is an integer between 0 and i-1. R = i-1.
Potential optimization: Since we only need DP_cur[i] for i from 1..n, and we will use it in next iteration, we only need to compute DP_cur. Good.
Now we need to ensure that for each j, prev_dp contains values for indices up to n. But when building segment tree, we include all indices up to n. However, indices > n? Actually we have indices 0..n, that's fine.
Now test with sample 3 quickly mentally.
Example 3: n=8, k=3, a = [7,7,8,7,7,8,1,7]. Answer 6.
We'll compute using algorithm to ensure it yields 6.
Let's simulate step by step:
First j=1: compute dp1[i] = distinct(1..i)
a: index:1:7, 2:7,3:8,4:7,5:7,6:8,7:1,8:7.
distinct prefix:
i=1: {7} ->1
i=2: {7} ->1
i=3: {7,8} ->2
i=4: {7,8} ->2
i=5: {7,8} ->2
i=6: {7,8}? actually 7 and 8 ->2
i=7: {7,8,1} ->3
i=8: {7,8,1} ->3
So dp1 = [0? ignore], values: dp1[1]=1, dp1[2]=1, dp1[3]=2, dp1[4]=2, dp1[5]=2, dp1[6]=2, dp1[7]=3, dp1[8]=3.
Now j=2: prev_dp = dp1 with dp1[0] = -inf.
Initialize segment tree with prev_dp: index0:-inf, 1:1,2:1,3:2,4:2,5:2,6:2,7:3,8:3.
Process i=1..8.
We'll track values for each t after updates, and dp_cur[i].
We need to compute dp_cur[i] for 2 segments covering first i.
We'll go through:
Initialize last[all]=0.
i=1 (val=7):
L=0,R=0: add +1 to [0,0] -> index0: -inf+1
Query [0,0] -> -inf -> dp2[1] = -inf.
last[7]=1.
i=2 (val=7):
L = last[7]=1, R=1: add +1 to [1,1] -> index1: 1+1=2.
Query [0,1] -> max(index0 negative, index1=2) ->2. So dp2[2]=2.
last[7]=2.
i=3 (val=8):
L = last[8]=0, R=2: add +1 to [0,2].
Before update: index0:-inf+1, index1:2, index2:1.
After: index0: -inf+2, index1:3, index2:2.
Query [0,2] -> max(index1=3, index2=2) =3 -> dp2[3]=3.
last[8]=3.
i=4 (val=7):
L = last[7]=2, R=3: add +1 to [2,3].
Before: index2:2, index3:2.
After: index2:3, index3:3.
Query [0,3] -> values: index0: -inf+2, index1:3, index2:3, index3:3 -> max=3 -> dp2[4]=3.
last[7]=4.
i=5 (val=7):
L = last[7]=4, R=4: add +1 to [4,4].
Before: index4=2.
After: index4=3.
Query [0,4] -> values: index1=3, index2=3, index3=3, index4=3 -> max=3 -> dp2[5]=3.
last[7]=5.
i=6 (val=8):
L = last[8]=3, R=5: add +1 to [3,5].
Before: index3=3, index4=3, index5=2.
After: index3=4, index4=4, index5=3.
Query [0,5] -> max among indices 0..5: index1=3, index2=3, index3=4, index4=4, index5=3 -> max=4 -> dp2[6]=4.
last[8]=6.
i=7 (val=1):
L = last[1]=0, R=6: add +1 to [0,6].
Before: index0:-inf+2, index1=3, index2=3, index3=4, index4=4, index5=3, index6=2.
After: index0:-inf+3, index1=4, index2=4, index3=5, index4=5, index5=4, index6=3.
Query [0,6] -> max = 5 (index3 or index4) => dp2[7]=5.
last[1]=7.
i=8 (val=7):
L = last[7]=5, R=7: add +1 to [5,7].
Before: index5=4, index6=3, index7=3 (prev_dp[7]=3).
After: index5=5, index6=4, index7=4.
Query [0,7] -> values: index1=4, index2=4, index3=5, index4=5, index5=5, index6=4, index7=4 -> max=5 -> dp2[8]=5.
last[7]=8.
So dp2[8] =5. That's maximum total value with 2 segments covering all 8 elements. For 2 segments, optimal might be? Let's think: Possibly [7,7,8,7,7,8] [1,7] -> distinct first segment: {7,8}=2, second: {1,7}=2 total 4. Or [7,7,8][7,7,8,1,7] -> first: {7,8}=2, second: {7,8,1}=3 total 5. So yes max 5.
Now j=3: we need dp3[8] =6 (expected). So we'll compute.
prev_dp = dp2 (with dp2[0] = -inf). dp2 values: we computed dp2[1]= -inf, dp2[2]=2, dp2[3]=3, dp2[4]=3, dp2[5]=3, dp2[6]=4, dp2[7]=5, dp2[8]=5.
Initialize segment tree with: index0:-inf, 1:-inf, 2:2, 3:3, 4:3, 5:3, 6:4, 7:5, 8:5.
Process i=1..8.
Initialize last all 0.
i=1 (val=7):
L=0,R=0 add +1 to [0,0] -> index0: -inf+1
Query [0,0] -> -inf -> dp3[1] = -inf.
last[7]=1.
i=2 (val=7):
L=last[7]=1,R=1 add +1 to [1,1] -> index1: -inf+1 (since index1 was -inf) => still -inf.
Query [0,1] -> max(index0:-inf+1, index1:-inf+1) = -inf -> dp3[2] = -inf.
last[7]=2.
i=3 (val=8):
L=last[8]=0,R=2 add +1 to [0,2].
Before: index0:-inf+1, index1:-inf, index2:2.
After: index0:-inf+2, index1:-inf+1, index2:3.
Query [0,2] -> max(index2=3) => dp3[3]=3.
last[8]=3.
i=4 (val=7):
L=last[7]=2,R=3 add +1 to [2,3].
Before: index2:3, index3:3.
After: index2:4, index3:4.
Query [0,3] -> max among index0,1,2,3: index2=4, index3=4 -> dp3[4]=4.
last[7]=4.
i=5 (val=7):
L=last[7]=4,R=4 add +1 to [4,4].
Before: index4=3.
After: index4=4.
Query [0,4] -> values: index2=4, index3=4, index4=4 -> max=4 => dp3[5]=4.
last[7]=5.
i=6 (val=8):
L=last[8]=3,R=5 add +1 to [3,5].
Before: index3=4, index4=4, index5=3.
After: index3=5, index4=5, index5=4.
Query [0,5] -> max among indices 0..5: index3=5, index4=5 -> dp3[6]=5.
last[8]=6.
i=7 (val=1):
L=last[1]=0,R=6 add +1 to [0,6].
Before: index0:-inf+2, index1:-inf+1, index2=4? Wait need current values after previous steps. Let's list values before i=7 step.
We need to track cumulative values properly.
Let's maintain a table:
Initialize: index0:-inf, 1:-inf, 2:2, 3:3, 4:3, 5:3, 6:4, 7:5, 8:5.
After i=1: add [0,0] +1 -> index0:-inf+1, others unchanged.
After i=2: add [1,1] +1 -> index1: -inf+1 (still -inf essentially), index0 remains -inf+1.
After i=3: add [0,2] +1.
Before i=3: index0:-inf+1, index1:-inf+1, index2:2, index3:3, index4:3, index5:3, index6:4, index7:5, index8:5.
After: index0:-inf+2, index1:-inf+2, index2:3, others unchanged.
After i=4: add [2,3] +1.
Before: index2:3, index3:3.
After: index2:4, index3:4.
After i=5: add [4,4] +1.
Before: index4:3 -> after: 4.
After i=6: add [3,5] +1.
Before: index3:4, index4:4, index5:3.
After: index3:5, index4:5, index5:4.
Now before i=7, values are:
index0: -inf+2 (still very negative)
index1: -inf+2 (negative)
index2: 4
index3: 5
index4: 5
index5: 4
index6: 4 (unchanged)
index7: 5 (unchanged)
index8: 5 (unchanged)
Now i=7 (val=1): L=0,R=6 add +1 to [0,6].
After update:
index0: -inf+3
index1: -inf+3
index2: 5
index3: 6
index4: 6
index5: 5
index6: 5 (since 4+1)
index7: 5 (unchanged, because not in range)
index8: 5 (unchanged)
Query [0,6] -> max among indices 0..6: index3=6, index4=6 -> dp3[7]=6.
last[1]=7.
i=8 (val=7):
L = last[7] =? last[7] was updated at i=5? Actually after i=5, last[7]=5; after i=6? val=8, so last[7] remains 5. After i=7? val=1, so last[7] still 5. So L=5, R=7 add +1 to [5,7].
Before i=8 (after i=7 updates): values as above. Specifically:
index5:5, index6:5, index7:5.
After update: index5:6, index6:6, index7:6.
(Other indices unchanged: index3=6, index4=6, etc.)
Query [0,7] -> max among indices 0..7: max(index3=6, index4=6, index5=6, index6=6, index7=6) = 6 -> dp3[8]=6.
Thus answer 6. Good.
So algorithm works.
Now we need to implement segment tree.
Potential improvements: Instead of rebuilding segment tree from scratch each j, we could reuse but not needed.
Now we must be cautious about memory and speed. We'll use iterative segment tree? Recursive with 4*(n+1) nodes is fine: 4*35001 ≈ 140k, times k we rebuild each iteration but not store all simultaneously. So memory fine.
Now code plan:
- Read n, k.
- Read array a (1-indexed) of size n+1.
- Define const long long NEG_INF = -1e15;
- vector prev_dp(n+1, NEG_INF);
- prev_dp[0] = 0;
- For j = 1 to k:
- Build segment tree with prev_dp.
- We'll write a class that takes vector& arr.
- vector cur_dp(n+1, NEG_INF);
- vector last(n+1, 0); // values up to n
- for i=1 to n:
- int val = a[i];
- int L = last[val];
- int R = i-1;
- if (L <= R) { st.update(L, R, 1); }
- cur_dp[i] = st.query(0, i-1);
- last[val] = i;
- // After loop, set cur_dp[0] = NEG_INF (already)
- prev_dp = cur_dp;
- Print prev_dp[n].
Check if prev_dp[n] could be NEG_INF? But k ≤ n, so there is always a valid partition (e.g., each segment one element), so answer should be ≥ k (since each segment at least 1). So positive.
Now segment tree implementation details: We'll implement with functions: build, update, query.
Potential issue: The segment tree uses recursion; for n=35000, recursion depth O(log n) is fine. But in C++, recursion for each update/query may cause some overhead but acceptable given 28 million operations? Each operation does about O(log n) recursive calls; total calls ≈ 2 * 1.75e6 * log2(35000) ≈ 21.75e616 = 56 million recursive calls. That might be borderline but likely okay in C++ with optimizations (O2). But we can optimize by using iterative segment tree with lazy? That's more complex. However, we can reduce constant by using a Fenwick tree-like structure for range add and prefix max? Not straightforward because we need range add and range max, not just prefix.
We could use a segment tree with iterative loops (non-recursive) and lazy propagation? That's more complex but doable. But given constraints, recursion should be okay. Many solutions in CF for this problem (C. Slastyona and Bakery?) use divide and conquer DP optimization with BIT? Actually known problem: "Slastyona and Sweets" maybe is from Codeforces Round #... I recall a problem "Bakery" with DP and segment tree. Many solutions use divide and conquer optimization with BIT, but also use segment tree.
We'll implement recursive segment tree.
But we should be careful: we have k up to 50, n up to 35000, and for each j we do 2 * n operations (update and query) each O(log n). That's about 50350002*~16 = 56 million function calls. In C++ with recursion, each call overhead is small; 56 million is fine within 2 seconds? Possibly okay. To be safe, we can implement segment tree with iterative style? Let's gauge: 56 million recursive calls, each call does few operations. Might be okay. But we also have building the tree each j O(n). That's negligible.
We could also use a data structure that supports range add and range max using a Fenwick tree with two BITs for range add and prefix sum? No, max not linear.
Alternative: Use the fact that we only need max over [0, i-1] which is a prefix max, but we have range adds that affect ranges that may start anywhere. However, we could maintain a Fenwick tree that supports range add and then we could use segment tree for max? Not trivial.
Given typical Codeforces solutions, they often use segment tree with lazy for this DP. So we'll proceed.
Now we need to be careful about potential stack overflow from deep recursion in building? Build uses recursion depth log n, fine.
We'll define segtree class with methods: update(l, r, val) and query(l, r). We'll store tree and lazy as vectors of long long.
Implementation:
class SegTree {
private:
int n;
vector tree, lazy;
void build(const vector& arr, int node, int l, int r) {
if (l == r) {
tree[node] = arr[l];
return;
}
int mid = (l + r) / 2;
build(arr, node2, l, mid);
build(arr, node2+1, mid+1, r);
tree[node] = max(tree[node2], tree[node2+1]);
}
void push(int node) {
if (lazy[node]) {
tree[node2] += lazy[node];
lazy[node2] += lazy[node];
tree[node2+1] += lazy[node];
lazy[node2+1] += lazy[node];
lazy[node] = 0;
}
}
void update(int node, int l, int r, int ql, int qr, long long val) {
if (ql > r || qr < l) return;
if (ql <= l && r <= qr) {
tree[node] += val;
lazy[node] += val;
return;
}
push(node);
int mid = (l + r) / 2;
update(node2, l, mid, ql, qr, val);
update(node2+1, mid+1, r, ql, qr, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
long long query(int node, int l, int r, int ql, int qr) {
if (ql > r || qr < l) return NEG_INF;
if (ql <= l && r <= qr) return tree[node];
push(node);
int mid = (l + r) / 2;
return max(query(node2, l, mid, ql, qr),
query(node2+1, mid+1, r, ql, qr));
}
public:
SegTree(const vector& arr) : n(arr.size() - 1) { // arr indexed 0..n
int size = n + 1;
tree.resize(4 * size);
lazy.assign(4 * size, 0);
build(arr, 1, 0, n);
}
void range_add(int l, int r, long long val) {
if (l > r) return;
update(1, 0, n, l, r, val);
}
long long range_max(int l, int r) {
if (l > r) return NEG_INF;
return query(1, 0, n, l, r);
}
};
Note: In constructor, we pass arr which includes index n. Our n in segtree is the max index (0..n). We'll store member n = arr.size() - 1 (since arr size = n+1). Then we allocate 4*(n+1) as tree size. In build, we call with l=0, r=n.
Now the DP loop:
for (int j = 1; j <= k; ++j) {
SegTree st(prev_dp);
vector cur_dp(n+1, NEG_INF);
vector last(n+1, 0); // note: a[i] values up to n (maybe 35000). So we need array size n+1.
for (int i = 1; i <= n; ++i) {
int val = a[i];
int L = last[val];
int R = i - 1;
st.range_add(L, R, 1);
cur_dp[i] = st.range_max(0, i-1);
last[val] = i;
}
prev_dp = move(cur_dp);
}
At the end, output prev_dp[n].
Now we should test with examples.
Edge Cases:
- k = 1: we compute directly.
- n = 1, k = 1: a[1]=x.
prev_dp init: [0, -inf].
j=1: build with prev_dp.
i=1: val = x, last[val]=0, R=0 => range_add(0,0,1) -> index0 becomes 0+1=1. query(0,0)=1 => cur_dp[1]=1. So answer=1. Correct.
- n = 5, k = 5: each segment one element -> answer = 5.
- n = 5, k = 2, array all same: e.g., 1 1 1 1 1. Then optimal partition: one segment of length L, other of length 5-L, each has distinct count 1, total 2. So answer 2. Our DP should yield 2.
Let's test: j=1: dp1[i] = 1 for all i. j=2: prev_dp: [ -inf,1,1,1,1,1] (index0 -inf). Process:
i=1: L=0,R=0 add -> index0 -inf+1, query -> -inf => cur[1] = -inf.
i=2: L=last[1]=1,R=1 add -> index1: 1+1=2, query [0,1] -> max(index1=2) => cur[2]=2.
i=3: L=last[1]=2,R=2 add -> index2:1+1=2, query [0,2] -> max(index1=2, index2=2) =>2 => cur[3]=2.
i=4: L=last[1]=3,R=3 -> index3:1+1=2, query ->2 => cur[4]=2.
i=5: L=last[1]=4,R=4 -> index4:1+1=2, query ->2 => cur[5]=2. So answer=2. Good.
Now, we should confirm that prev_dp[0] for j>1 is -inf. In j=2 we had prev_dp[0] = -inf, so we never use t=0. That's correct because we need at least one segment already (j-1 segments) covering some elements; t=0 would mean no elements covered by previous segments, which is impossible for j-1>=1.
Now, potential performance improvements: Use array for last (size n+1) and reset each j; we can also use vector and assign 0 each j.
Now memory: cur_dp and prev_dp each size 35001, fine.
Now we need to think about the possibility of using int instead of long long for DP values. Max sum <= 1.75e6 fits in int. However, we use NEG_INF = -1e9, which also fits in int. But when we do addition, we might add many times to an index that starts as -1e9, resulting in up to -1e9 + 35000 = -965000, still fits. So we could use int. However, to avoid overflow if we ever use large negative, long long is safer. But we can use int. But note: In segment tree, lazy values can accumulate; the max value after many updates could be up to 1.75e6 + number of updates to that index? Actually DP_cur values are at most 1.75e6, but the segment tree stores DP_prev[t] + distinct(t+1,i) which is at most about 1.75e6 as well (since DP_prev[t] is sum of distinct counts for j-1 segments, max (j-1)n, and distinct(t+1,i) ≤ n, sum ≤ jn). So still within int. But we used NEG_INF = -1e9, which is safe int. However, if we use int, we must be careful about overflow when adding to -1e9 many times: -1e9 + 35000 = -999650000? Actually -1e9 is -1000000000, plus 35000 = -999650000, still within 32-bit int (which can hold up to about ±2.1e9). So int is safe. But to be safe with large negative values, we can use int. But we'll use long long for peace of mind.
Now, we need to ensure that our segment tree's NEG_INF is consistent. If we use long long NEG_INF = -1e15, and we add up to 35000, it's still far from zero, so fine.
Now, we also need to consider that the segment tree's update and query functions may be called many times. We can micro-optimize by passing parameters as ints, using inline, etc. But not necessary.
Now, the segment tree building each j: O(n). We'll implement build recursively. That's okay.
Alternative: we could avoid building a new tree each j by using an existing tree and resetting values, but easier to rebuild.
Now we should test with random small n and brute force to ensure correctness. But not needed for solution.
Now final code structure:
#include <bits/stdc++.h>
using namespace std;
const long long NEG_INF = -1e15;
class SegTree {
// as above
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<int> a(n+1);
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
vector<long long> prev_dp(n+1, NEG_INF);
prev_dp[0] = 0;
for (int j = 1; j <= k; ++j) {
SegTree st(prev_dp);
vector<long long> cur_dp(n+1, NEG_INF);
vector<int> last(n+1, 0); // value up to n
for (int i = 1; i <= n; ++i) {
int val = a[i];
int L = last[val];
int R = i - 1;
st.range_add(L, R, 1);
cur_dp[i] = st.range_max(0, i-1);
last[val] = i;
}
prev_dp = cur_dp;
}
cout << prev_dp[n] << "\n";
return 0;
}
Now consider if k > n? Not possible as per constraints: k ≤ min(n,50). So fine.
Potential bug: In j=1, prev_dp[0] = 0, others -inf. In the loop, for i=1, we update range [0,0] +1 and query [0,0] => 1. Works. However, note that for i=1, we query [0,0] which includes index0. That's valid because t=0 means first segment starts at 1, so DP_prev[0]=0 + distinct(1..i). Good.
For j>1, we query [0,i-1], which includes index0. But index0 is -inf, so it's ignored. That's fine.
Now we must ensure that for j>1, prev_dp[0] is indeed -inf. In our code, after first iteration, we set cur_dp (for j=1) and assign prev_dp = cur_dp. Our cur_dp is initialized with NEG_INF for all indices, then we fill cur_dp[i] for i from 1 to n. So cur_dp[0] remains NEG_INF. So for j=2, prev_dp[0] = NEG_INF. Good.
Now also need to handle the case where the segment tree's range_max(l, r) with l>r returns NEG_INF. That's safe.
Now we might consider using fast I/O.
Now test with sample inputs.
We'll mentally test with provided examples.
Example1: n=4,k=1,a=[1,2,2,1]. Already did, answer 2.
Example2: answer 5.
Example3: answer 6.
Now verify with edge: n=35000, k=50, random. Should be fine.
Potential improvement: For each j, we can avoid using vector cur_dp by writing into prev_dp after computing all, but we need prev_dp for building tree, so we need separate.
Now the segment tree implementation: we must ensure that the build function uses the correct n (max index). In constructor, we set n = arr.size() - 1, but arr.size() should be n+1. In main, we have prev_dp size n+1, so okay.
Now we must be careful: In range_add and range_max, we call update/query with l and r inclusive. Our implementation uses inclusive.
Now about the lazy propagation: push should be called before recursing. In query, we also need to push to ensure children have up-to-date values.
Now we also need to consider that when we call range_add with L and R, we might be adding to indices that are beyond the current i? Actually R = i-1, L = last[val] ≤ i-1, so within 0..n, but when i is small, R is small, so fine.
Now time complexity: each update and query O(log n). There's also the cost of building tree O(n) each j, negligible.
Now implement.
But we need to ensure that our segment tree's memory allocation each j (via constructor) is not too heavy: each time we create a new SegTree object, the vector tree and lazy are allocated. That's O(n) per iteration, okay.
But we might want to reuse the same tree by resetting values. Not needed.
Now final code.
One more test: k=n. Example: n=3,k=3,a=[1,2,3]. Expected answer 3.
Compute: j=1: dp1[1]=1,dp1[2]=2,dp1[3]=3.
j=2: as earlier, dp2[3]=? Actually partition into 2 segments: possible max = 3? Let's compute: possibilities: [1][2,3] => 1+2=3; [1,2][3] =>2+1=3. So dp2[3]=3.
j=3: dp3[3]=? partitions: [1][2][3] =>3. Our algorithm: prev_dp for j=3 is dp2: values: dp2[1]? dp2[1] = -inf, dp2[2] = 2? Actually for n=3, j=2: dp2[1] -inf, dp2[2] = 2? Check: dp2[2] should be max with 2 segments covering 2 elements: only [1][2] =>1+1=2, so yes dp2[2]=2. dp2[3]=3. Then j=3: prev_dp = [ -inf, -inf, 2, 3]. Process:
i=1: update add [0,0]+1 -> index0:-inf+1, query [0,0] = -inf -> cur[1] = -inf.
i=2: val=2, last[2]=0? initially 0. So L=0,R=1 add +1 to [0,1]: index0:-inf+2, index1:-inf+1. Query [0,1] -> max negative? Actually index1 is -inf+1, still negative. So cur[2] = -inf? But we need cur[2] = -inf (since 3 segments covering 2 elements impossible). Good.
i=3: val=3, last[3]=0, L=0,R=2 add +1 to [0,2]: index2:2+1=3. Query [0,2] -> max=3 => cur[3]=3. So answer 3. Good.
Now we also need to ensure that for j=2, dp2[2] = 2, not 3. Our earlier simulation gave 2, correct.
Now we have to consider if there's any better DP optimization: but our solution is fine.
Now, double-check for potential bug: When we do range_add(L, R, 1) and then query, we are using the updated values for current i. That's correct.
Now, confirm that we are not double counting the distinct contribution for intervals where the new element already existed. Our update only adds +1 to intervals where left > last occurrence. That's correct.
Now we need to think about the possibility of integer overflow in lazy propagation if we use long long and many adds? But total adds per index ≤ n, and number of indices n, so lazy values ≤ n, safe.
Now we can implement.
But there is one more nuance: In the segment tree, we use build which recursively builds from array. The array values may be NEG_INF (large negative). Adding 1 to them many times might make them less negative but still not overflow. But we should ensure that when we do tree[node] += val, if tree[node] is NEG_INF and val positive, it becomes less negative, but that's fine.
Now about speed: Each j loop, we also allocate vector last of size n+1. That's O(n) each iteration, total O(k*n) memory allocation but okay. We could reuse and reset using memset? But vector assignment is fine.
Now final code.
But wait: There's a known alternative: Use divide and conquer DP optimization with BIT to compute distinct counts quickly, but our method is simpler.
Now final step: Write the code in the answer.
We should also consider the possibility of using a Fenwick tree to maintain DP values and a "difference array" for distinct counts? But segment tree is fine.
Now I'll produce final answer.
But we might want to micro-optimize: Use arrays instead of vectors for tree? But vectors are fine.
Now check memory: 4*(n+1) = 140k * 8 bytes = ~1.12 MB per tree. But we allocate a new one each iteration, but old one is destroyed, so peak memory ~2 MB plus DP arrays. So fine.
Now final answer.
However, there is a known problem: "C. Slastyona and Sweets" maybe uses this exact DP with segment tree. I recall that the standard solution is indeed DP with segment tree and range updates.
One more check: In the DP transition, we consider t from 0 to i-1 inclusive. That's correct. But we must also ensure that for t = i-1, distinct(i,i)=1 and DP_prev[i-1] must be valid (i-1 >= j-1). That is automatically handled because DP_prev[i-1] is -inf if invalid.
Now confirm with an example where j=2 and i=2: t can be 1? t=1 means first segment covers first element, second segment covers element 2. DP_prev[1] must be DP[1][1] which is distinct(1,1)=1 (since j-1=1). So valid if j-1 <= 1. For j=2, j-1=1, so DP_prev[1] should be defined. In our algorithm, after j=1, we have DP[1][1] = distinct(1,1)=1, so DP_prev[1]=1. So that works.
Now edge: When i = j-1? For example j=2, i=1, we query t from 0 to 0, but t=0 DP_prev[0] = -inf, so dp_cur[1] = -inf. Good because cannot have 2 segments covering 1 element.
Now all good.
Now I'll write the final code.
But we need to be careful about the data type of last array: values up to n (max 35000), so int is fine.
Now final answer with explanation.
Now I'm ready to produce the final output. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll NEG_INF = -1e15; // sufficiently small for "minus infinity"
// Segment tree with lazy propagation for range add and range max
class SegTree {
int n; // indices from 0 to n
vector tree, lazy;
void build(const vector<ll>& a, int node, int l, int r) {
if (l == r) {
tree[node] = a[l];
return;
}
int mid = (l + r) / 2;
build(a, node * 2, l, mid);
build(a, node * 2 + 1, mid + 1, r);
tree[node] = max(tree[node * 2], tree[node * 2 + 1]);
}
void push(int node) {
if (lazy[node]) {
tree[node * 2] += lazy[node];
lazy[node * 2] += lazy[node];
tree[node * 2 + 1] += lazy[node];
lazy[node * 2 + 1] += lazy[node];
lazy[node] = 0;
}
}
void update(int node, int l, int r, int ql, int qr, ll val) {
if (ql > r || qr < l) return;
if (ql <= l && r <= qr) {
tree[node] += val;
lazy[node] += val;
return;
}
push(node);
int mid = (l + r) / 2;
update(node * 2, l, mid, ql, qr, val);
update(node * 2 + 1, mid + 1, r, ql, qr, val);
tree[node] = max(tree[node * 2], tree[node * 2 + 1]);
}
ll query(int node, int l, int r, int ql, int qr) {
if (ql > r || qr < l) return NEG_INF;
if (ql <= l && r <= qr) return tree[node];
push(node);
int mid = (l + r) / 2;
return max(query(node * 2, l, mid, ql, qr),
query(node * 2 + 1, mid + 1, r, ql, qr));
}
public:
// a is expected to have size n+1 (indices 0..n)
SegTree(const vector& a) {
n = (int)a.size() - 1;
tree.resize(4 * (n + 1));
lazy.assign(4 * (n + 1), 0);
build(a, 1, 0, n);
}
void range_add(int l, int r, ll val) {
if (l > r) return;
update(1, 0, n, l, r, val);
}
ll range_max(int l, int r) {
if (l > r) return NEG_INF;
return query(1, 0, n, l, r);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<int> a(n + 1);
for (int i = 1; i <= n; ++i)
cin >> a[i];
// dp_prev[t] = DP[t][j-1]
vector<ll> dp_prev(n + 1, NEG_INF);
dp_prev[0] = 0; // DP[0][0] = 0
for (int j = 1; j <= k; ++j) {
// build segment tree with current dp_prev values
SegTree st(dp_prev);
vector<ll> dp_cur(n + 1, NEG_INF);
vector<int> last(n + 1, 0); // last occurrence of each value (1..n)
for (int i = 1; i <= n; ++i) {
int val = a[i];
int L = last[val];
int R = i - 1;
st.range_add(L, R, 1); // intervals that get +1
dp_cur[i] = st.range_max(0, i - 1); // best cut for first i
last[val] = i;
}
dp_prev = move(dp_cur); // prepare for next layer
}
cout << dp_prev[n] << "\n";
return 0;
}