列表

详情


NC220446. Cities

描述

Bob lives in a chaotic country with cities in a row, numbered from to . These cities are owned by different lords, and the -th cities currently belongs to the -th lord. To simply problems, we assume there are lords in the country, and they are also numbered from to . Some lords may take control of multiple cities, while some new-born lords have not got any cities yet.

Obviously, the greedy lords are not satisfied with the number of territories they have, so the country is constantly at war. Bob wants to change that, by making all the cities belong to the same lord!

Bob can perform some magical operations to support his grand plan. With the help of each magic, Bob can do the following:


As magics are really tiring, Bob wants to know the minimum number of such operations he needs to use to make all the cities belong to one lord.

The following picture shows an example where . Different shapes are used to represent cities belonging to different lords. As shown in the picture, the minimum number of magic operations used is 2.


输入描述

The first line contains a single integer  --- the number of test cases.

The first line of each test case contains an integers --- the number of cities in the country.

The second line of each test case contains n integers a_i --- the i-th city was originally owned by the a_i-th lord. It is guaranteed that 

It is guaranteed that the sum of n over all test cases doesn't exceed 6000.

输出描述

For each test case, print a single integer indicating the answer.

示例1

输入:

2
8
4 3 1 2 1 1 3 3
5
1 2 3 2 1

输出:

3
2

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(clang++11) 解法, 执行用时: 903ms, 内存消耗: 67448K, 提交时间: 2021-04-19 11:19:10

#include<cstdio>
#include<algorithm>
#define rep(i,l,r) for (int i=(l); i<=(r); i++)
using namespace std;

const int M=5010;
int n,T,a[M],dp[M][M],las[M],b[M];

int main(){
	for (scanf("%d",&T); T--; ){
		scanf("%d",&n);
		rep(i,1,n) b[i]=0;
		rep(i,1,n) scanf("%d",&a[i]),las[i]=b[a[i]],b[a[i]]=i;
		rep(i,2,n) rep(l,1,n-i+1){
			int r=l+i-1,k=las[r];
			dp[l][r]=1e9;
			while (k>=l) dp[l][r]=min(dp[l][r],dp[l][k]+dp[k+1][r]),k=las[k];
			dp[l][r]=min(dp[l][r],dp[l][r-1]+1);
			dp[l][r]=min(dp[l][r],dp[l+1][r]+1);
		}
		printf("%d\n",dp[1][n]);
	}
	return 0;
}

上一题