Flood Fill 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.

思路:先对原数据去重,之后是区间dp。个人认为,这个dp用递归写,又简单又好想。

# include <iostream>
# include <cstdio>
# include <cmath>
#include<cstring>
#include<queue>
#include<map>
#define ll long long
# define pi acos(-1.0)
#define mod 998244353
#define inf 0x3f3f3f3f
using namespace std;
ll n,c[1008611],a[1008611];
ll dp[5005][5005],cnt,ans;
ll dfs(ll l,ll r){
    if(l==r){
        return 0;
    }
    if(dp[l][r]!=-1)return dp[l][r];
    if(a[l]==a[r])
         ans=dfs(l+1,r-1)+1;
    else
       ans=min(dfs(l+1,r)+1,dfs(l,r-1)+1);
    dp[l][r]=ans;
    return ans;
}
int main(){
    scanf("%lld",&n);
    for(ll i=1;i<=n;i++){
        scanf("%lld",&c[i]);
    }
    cnt=2;
    a[1]=c[1];
    for(ll i=2;i<=n;i++){
        if(c[i]==c[i-1])continue;
            a[cnt++]=c[i];
    }
    cnt--;
    memset(dp, -1, sizeof(dp));
    printf("%lld\n",dfs(1,cnt));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiao_you_you/article/details/89403012