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
Copy
4 5 2 2 1
output
Copy
2
input
Copy
8 4 5 2 2 1 3 5 5
output
Copy
4
input
Copy
1 4
output
Copy
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,2,2,1]
- [5,5,5,1][5,5,5,1]
- [1,1,1,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,4 in that order.
In the third example, the line already consists of one color only.
思路:
1,简单的就复杂点,复杂的就简单点
2,dp[l][r][k]区间dp从l到r向k方向,有最小的步数dp,因为向左向右不清楚,所以需要优雅的暴力一下
代码:
int a[5010],dp[5010][5010][2];
void solve(){//dp是优雅地爆力,向左还是向右,不确定,应该全试一遍
int n;
cin>>n;
for(int i=1;i<=n;++i)cin>>a[i];
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){//初始化
if(i==j)dp[i][j][0]=dp[i][j][1]=0;
else dp[i][j][0]=dp[i][j][1]=inf;
}
}
for(int r=1;r<=n;++r){
for(int l=r;l>=1;--l){
for(int k=0;k<2;++k){
int c=k?a[r]:a[l];
if(l>=1){
dp[l-1][r][0]=min(dp[l-1][r][0],dp[l][r][k]+(a[l-1]!=c));//向左走
}
if(r<=n){
dp[l][r+1][1]=min(dp[l][r+1][1],dp[l][r][k]+(a[r+1]!=c));//向右走
}
}
}
}cout<<min(dp[1][n][0],dp[1][n][1])<<'\n';
}