NC220446. Cities
描述
输入描述
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 --- the i-th city was originally owned by the -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; }