题目描述:
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
Enjoy erasing Tenzing, identified as Accepted!
Tenzing has nn balls arranged in a line. The color of the ii-th ball from the left is aiai.
Tenzing can do the following operation any number of times:
- select ii and jj such that 1≤i<j≤|a|1≤i<j≤|a| and ai=ajai=aj,
- remove ai,ai+1,…,ajai,ai+1,…,aj from the array (and decrease the indices of all elements to the right of ajaj by j−i+1j−i+1).
Tenzing wants to know the maximum number of balls he can remove.
Input
Each test contains multiple test cases. The first line of input contains a single integer tt (1≤t≤1031≤t≤103) — the number of test cases. The description of test cases follows.
The first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of balls.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n) — the color of the balls.
It is guaranteed that sum of nn of all test cases will not exceed 2⋅1052⋅105.
Output
For each test case, output the maximum number of balls Tenzing can remove.
input
2
5
1 2 2 3 3
4
1 2 1 2
output
4
3
思路分析:dp,dp[i]代表区间[1,i]所能删除的最大数量。
代码:
#include<iostream>
#include<cstring>
using namespace std;
int a[200005],dp[200005],b[200005];
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
dp[i]=0;
b[a[i]]=-1;
}
dp[0]=0;
for(int i=1;i<=n;i++){
if(b[a[i]]!=-1)
{
int ans=max(dp[b[a[i]]-1]+i+1-b[a[i]],dp[b[a[i]]]+i-b[a[i]]);
dp[i]=max(dp[i-1],ans);
}
else
dp[i]=dp[i-1];
b[a[i]]=i;
}
cout<<dp[n]<<endl;
}
}