传送门
文章目录
- 题意:
- 思路:
题意:
给你一个有nnn个像素的图像,每个像素都有一个颜色aia_iai,保证每种颜色的图像不会超过202020个。你现在每次可以选择一个颜色,并选择一段连续的像素,要求连续的像素的颜色必须相同,让后将这段像素变成选择的颜色,问最少需要进行多少次操作,才能使得所有像素的颜色相同。
1≤n≤3e3,1≤ai≤n1\le n\le 3e3,1\le a_i\le n1≤n≤3e3,1≤ai≤n
思路:
考虑[a,b,a][a,b,a][a,b,a]这种形式的,肯定是将bbb变成aaa是最优的,而不是将aaa变成bbb,再看一下数据范围,就能确定是一个20∗n220*n^220∗n2的区间dpdpdp了。
设dp[i][j]dp[i][j]dp[i][j]代表将[i,j][i,j][i,j]变成一种颜色的最少操作次数,根据上面的分析,我们将所有颜色变成两头的颜色答案一定不劣,所以先不管端点什么颜色,容易写出来其中的一个转移方程f[i][j]=min(f[i][j−1]+1,f[i+1][j]+1)f[i][j]=min(f[i][j-1]+1,f[i+1][j]+1)f[i][j]=min(f[i][j−1]+1,f[i+1][j]+1),因为可以将其余区间的所有颜色都变成端点颜色,为了方便我们假设将其都变成左端点的颜色。
考虑每种颜色都不会超过202020个,由于将其变成左端点的颜色,所以暴力枚举与左端点颜色相同的点,然后将其分成两个区间进行转移即可。
复杂度O(20n2)O(20n^2)O(20n2)
// Problem: E. Paint
// Contest: Codeforces - Codeforces Round #743 (Div. 2)
// URL: https://codeforces.com/contest/1573/problem/E
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#include<random>
#include<cassert>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid ((tr[u].l+tr[u].r)>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;const int N=3010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;int n;
int f[N][N];
int a[N],ne[N];
int pos[N];int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);int _; scanf("%d",&_);while(_--) {scanf("%d",&n);for(int i=1;i<=n;i++) scanf("%d",&a[i]),pos[a[i]]=0;for(int i=n;i>=1;i--) {if(!pos[a[i]]) ne[i]=n+1;else ne[i]=pos[a[i]];pos[a[i]]=i; }for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i!=j) f[i][j]=INF; else f[i][j]=0;for(int len=2;len<=n;len++) {for(int l=1;l+len-1<=n;l++) {int r=l+len-1;f[l][r]=min(f[l+1][r]+1,f[l][r-1]+1);for(int k=ne[l];k<=r;k=ne[k]) {f[l][r]=min(f[l][r],f[l][k-1]+f[k][r]);}}}printf("%d\n",f[1][n]);}return 0;
}
/**/