Codeforces 834 D. The Bakery (线段树+dp)
Posted 小坏蛋_千千
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces 834 D. The Bakery (线段树+dp)相关的知识,希望对你有一定的参考价值。
Description
Some time ago Slastyona the Sweetmaid decided to open her own bakery! She bought required ingredients and a wonder-oven which can bake several types of cakes, and opened the bakery.
Soon the expenses started to overcome the income, so Slastyona decided to study the sweets market. She learned it’s profitable to pack cakes in boxes, and that the more distinct cake types a box contains (let’s denote this number as the value of the box), the higher price it has.
She needs to change the production technology! The problem is that the oven chooses the cake types on its own and Slastyona can’t affect it. However, she knows the types and order of n cakes the oven is going to bake today. Slastyona has to pack exactly k boxes with cakes today, and she has to put in each box several (at least one) cakes the oven produced one right after another (in other words, she has to put in a box a continuous segment of cakes).
Slastyona wants to maximize the total value of all boxes with cakes. Help her determine this maximum possible total value.
Input
The first line contains two integers n and k (1 ≤ n ≤ 35000, 1 ≤ k ≤ min(n, 50)) – the number of cakes and the number of boxes, respectively.
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ n) – the types of cakes in the order the oven bakes them.
Output
Print the only integer – the maximum total value of all boxes with cakes.
Examples input
4 1
1 2 2 1
Examples output
2
题意
有 n n 个数字分成 段,每一段的价值是其中不同数字的个数,求总的最大价值。
思路
很容易想到的一种 dp 思路,其中, dp[i][k] d p [ i ] [ k ] 代表把前 i i 个数字分成 段所能得到的最大价值。
显然:
- 当 k=1 k = 1 时, dp[i][1] d p [ i ] [ 1 ] 为前 i i 个数字的不同个数
- 当 时, dp[i][k]=max1≤j≤idp[j−1][k−1]+c[j][i] d p [ i ] [ k ] = max 1 ≤ j ≤ i d p [ j − 1 ] [ k − 1 ] + c [ j ] [ i ] ( c[j][i] c [ j ] [ i ] 代表区间 [j,i] [ j , i ] 数字的不同个数)
算得 dp 数组中的每一个值朴素的做法需要 O(n) O ( n ) 的时间,因此这样总的时间复杂度为 O(k×n2) O ( k × n 2 ) 。
我们考虑用线段树来优化状态的转移,转移方程中第 k k 行的值取决于第 行的值,因此我们在算出第 k−1 k − 1 行以后,考虑建立该行的线段树,从而快速的求出第 k k 行的值。
但是我们发现,在求第 行值的时候 c[j][i] c [ j ] [ i ] 会随着 i i 的变化而变化。
我们令树的叶子节点 表示 dp[j−1][k−1]+c[j][i] d p [ j − 1 ] [ k − 1 ] + c [ j ] [ i ] ,则状态转移方程变为了 dp[i][k]=max1≤j≤ia[j] d p [ i ] [ k ] = max 1 ≤ j ≤ i a [ j ] ,此时 dp[j−1][k−1] d p [ j − 1 ] [ k − 1 ] 是已知的,我们只需要考虑由 i−1 i − 1 到 i i 时 的变化。
设第 i i 个数字为 y y ,前一个出现 y y 的位置为 pre[y] p r e [ y ] ,那么显然当前所增加的数字 y y 会对区间 [pre[y]+1,i] [ p r e [ y ] + 1 , i ] 产生影响,因此 c[s,i],(s∈[pre[y]+1,i]) c [ s , i ] , ( s ∈ [ p r e [ y ] + 1 , i ] ) 需要加 1 1 ,这样便可以成功从 CodeForces 834D The Bakery
D. Vasya And The Matrix(Educational Codeforces Round 48)
Codeforces Round #502 D. The Wu(状压预处理)
Codeforces Round #526 (Div. 2) D. The Fair Nut and the Best Path
codeforces 876 D. Sorting the Coins
Codeforces Round #270 D. Design Tutorial: Inverse the Problem