[[IntervalDP|IntervalDP]]

You are given an array AA of length NN consisting of non-negative integers.

You have another array cc of the same length. Initially, ci=0c_{i}=0 for all 1iN1 \leqslant i \leqslant N.

You can perform the following operation any number of times:

  • Choose a non-negative integer xx and a subarray [l,r][l, r], then set ci:=xc_{i} := x for all lirl \le i \le r.

Find the minimum number of operations required to transform the array cc into the target array AA.

Note that the target array AA may contain zeros.

1N5001 \leqslant N \leqslant 500
0AiN0 \leqslant A_{i} \leqslant N

给定数组 AA
初始有一个全为 0 的数组,每次任选一个非负整数 xx,任选一个区间 [l,r][l,r],把区间 [l,r][l,r] 都变成 xx,最少需要多少次得到目标数组? 目标数组可能包含 0

第一步:不考虑 0,区间 DP

  • 初始状态:fi,i=1f_{i,i} = 1
  • fi,j=minik<j{fi,k+fk+1,j}f_{i,j} = \min_{i \le k < j} \{f_{i,k} + f_{k+1,j} \}
  • 如果 A[i]=A[j]A[i] = A[j]fi,j=fi+1,jf_{i,j} = f_{i+1,j}

第二步:考虑 0,线性 DP

  • gig_i 表示将初始全 0 数组的前缀 [1i][1 \dots i] 变为目标数组 A[1i]A[1 \dots i] 的最少操作次数。
  • 初始状态:g0=0g_0 = 0
  • 如果 A[i]=0A[i] = 0 gi=gi1g_i = g_{i-1}
  • gi=min0k<i{gk+fk+1,i}g_i = \min_{0 \le k < i} \{g_k + f_{k+1,i} \}
  • 最终答案:gng_n