CF 1114D-Flood Fill-n2复杂度的区间dp

Description

You are given a line of n colored squares in a row, numbered from 1 to n from left to right. The i-th square initially has the color ci.
Let’s say, that two squares i and j belong to the same connected component if ci=cj, and ci=ck for all k satisfying i<k<j. In other words, all squares on the segment from i to j should have the same color.
For example, the line [3,3,3] has 1 connected component, while the line [5,2,4,4] has 3 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 n (1≤n≤5000) — the number of squares.
The second line contains integers c1,c2,…,cn (1≤ci≤5000) — the initial colors of the squares.

Output

Print a single integer — the minimum number of the turns needed.

Sample Input

8
4 5 2 2 1 3 5 5

Sample Output

4

核心思想:

O(n2)的复杂度写区间dp。

代码如下:

#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
const int N=5e3+5;
int dp[N][N],a[N];
int main()
{
	int n;
	scanf("%d",&n);
	n=2;
	scanf("%d",&a[1]);
	//压缩连续相等的值 
	while(scanf("%d",&a[n])!=EOF)
		if(a[n]!=a[n-1])
			n++;
	n--;
	for(int d=2;d<=n;d++)
		for(int i=1;i+d-1<=n;i++)
		{
			int j=i+d-1;
			//相等则中间区间+1 
			if(a[i]==a[j])
			{
				if(d==2)
					dp[i][j]=0;
				else
					dp[i][j]=dp[i+1][j-1]+1;
			}
			else
			{
				//源点只有一个,来自左区间或右区间 
				dp[i][j]=min(dp[i][j-1],dp[i+1][j])+1;
			}
		}
	printf("%d\n",dp[1][n]);
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值