https://cn.vjudge.net/problem/CodeForces-1114D
You are given a line of nn colored squares in a row, numbered from 11 to nn from left to right. The ii-th square initially has the color cici.
Let's say, that two squares ii and jj belong to the same connected component if ci=cjci=cj, and ci=ckci=ck for all kk satisfying i<k<ji<k<j. In other words, all squares on the segment from ii to jj should have the same color.
For example, the line [3,3,3][3,3,3] has 11 connected component, while the line [5,2,4,4][5,2,4,4] has 33 connected components.
The game "flood fill" is played on the given line as follows:
- At the start of the game you pick any starting square (this is not counted as a turn).
- Then, in each game turn, change the color of the connected component containing the starting square to any other color.
Find the minimum number of turns needed for the entire line to be changed into a single color.
Input
The first line contains a single integer nn (1≤n≤50001≤n≤5000) — the number of squares.
The second line contains integers c1,c2,…,cnc1,c2,…,cn (1≤ci≤50001≤ci≤5000) — the initial colors of the squares.
Output
Print a single integer — the minimum number of the turns needed.
Examples
Input
4 5 2 2 1
Output
2
Input
8 4 5 2 2 1 3 5 5
Output
4
Input
1 4
Output
0
Note
In the first example, a possible way to achieve an optimal answer is to pick square with index 22 as the starting square and then play as follows:
- [5,2,2,1]
- [5,5,5,1]
- [1,1,1,1]
In the second example, a possible way to achieve an optimal answer is to pick square with index 55 as the starting square and then perform recoloring into colors 2,3,5,42,3,5,4in that order.
In the third example, the line already consists of one color only.
题意:连续的几个颜色相同的格子称为一个连通块。选一个点为起点,每个操作是把所在连通块变一个颜色,求把整个区间染成同色需要的最少操作数。(注意,每次只能改变所在连通块的颜色,不能任选连通块,除了最开始时)
对于区间[L,R],最优的方案要么是全变成L处的颜色,要么全变成R处的颜色
#include<bits/stdc++.h>
#pragma GCC optimize(3)
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
using namespace std;
typedef long long ll;
const int N=5e3+5;
int c[N];
int dp[N][N][2];
inline int judge(int a,int b){
return c[a]==c[b]?0:1;
}
int dfs(int l,int r,int flag){
if(dp[l][r][flag]!=-1) return dp[l][r][flag];
if(l==r) return 0;
int ans=N;
if(flag==0){
ans=min(ans,dfs(l+1,r,0)+judge(l,l+1));
ans=min(ans,dfs(l+1,r,1)+judge(l,r));
}
else{
ans=min(ans,dfs(l,r-1,0)+judge(l,r));
ans=min(ans,dfs(l,r-1,1)+judge(r-1,r));
}
return dp[l][r][flag]=ans;
}
int main(){
int n;
scanf("%d",&n);
c[0]=N;
int m=0;
for(int i=1;i<=n;i++) {
int x;
scanf("%d",&x);
if(x!=c[m]) c[++m]=x;
}
n=m;
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
dp[i][j][0]=dp[i][j][1]=-1;
}
}
int ans=min(dfs(1,n,0),dfs(1,n,1));
printf("%d\n",ans);
return 0;
}