首先进行缩点,这样最终数组中最长的同色块长度为1;在套用区间dp的模板
状态转移方程
ACcode
2022/7/15日更新一个缩点方法
vector<int>a;
a.erase(unique(a.begin(), a.end()), a.end());
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int long long
#define endl '\n'
#define lowbit(x) x &(-x)
#define mh(x) memset(x, -1, sizeof h)
#define debug(x) cerr << #x << "=" << x << endl;
const int N = 2e2 + 10;
const int mod = 998244353;
const double esp = 1e-6;
const double pi = acos(-1);
typedef pair<int, int> PII;
signed main()
{
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++)
cin >> a[i];
a.erase(unique(a.begin(), a.end()), a.end());
n = a.size() - 1;
vector<vector<int>> dp((n + 1), vector<int>(n + 1));
for (int len = 2; len <= n; len++)
{
for (int l = 1; l + len - 1 <= n; l++)
{
int r = l + len - 1;
if (a[l] == a[r])
dp[l][r] = dp[l + 1][r - 1] + 1;
else
dp[l][r] = min(dp[l + 1][r] + 1, dp[l][r - 1] + 1);
}
}
cout << dp[1][n] << endl;
}
ACcode
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int mod = 1e9 + 7, N = 1 << 13;
signed main()
{
cin.tie(0)->sync_with_stdio(0);
int n;
cin >> n;
vector<int> a{0};
for (int i = 1; i <= n; i++)//读入时缩点
{
int x;
cin >> x;
if (a.back() != x)
{
a.push_back(x);
}
}
n = a.size() - 1;
vector<vector<int>> dp(n + 1, vector<int>(n + 1));
for (int len = 2; len <= n; len++)
{
for (int l = 1; l + len - 1 <= n; l++)
{
int r = l + len - 1;
if (a[l] == a[r])
{
dp[l][r] = dp[l + 1][r - 1] + 1;
}
else
{
dp[l][r] = min(dp[l + 1][r], dp[l][r - 1]) + 1;
}
}
}
cout << dp[1][n] << endl;
}