Three Blocks Palindrome (easy version) CodeForces - 1335E1(暴力+二分)

The only difference between easy and hard versions is constraints.

You are given a sequence a consisting of n positive integers.

Let’s define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [a,a,…,ax,b,b,…,by,a,a,…,ax]. There x,y are integers greater than or equal to 0. For example, sequences [], [2], [1,1], [1,2,1], [1,2,2,1] and [1,1,2,1,1] are three block palindromes but [1,2,3,2,1], [1,2,1,2,1] and [1,2] are not.

Your task is to choose the maximum by length subsequence of a that is a three blocks palindrome.

You have to answer t independent test cases.

Recall that the sequence t is a a subsequence of the sequence s if t can be derived from s by removing zero or more elements without changing the order of the remaining elements. For example, if s=[1,2,1,3,1,2,1], then possible subsequences are: [1,1,1,1], [3] and [1,2,1,3,1,2,1], but not [3,2,3] and [1,1,1,1,2].

Input
The first line of the input contains one integer t (1≤t≤2000) — the number of test cases. Then t test cases follow.

The first line of the test case contains one integer n (1≤n≤2000) — the length of a. The second line of the test case contains n integers a1,a2,…,an (1≤ai≤26), where ai is the i-th element of a. Note that the maximum value of ai can be up to 26.

It is guaranteed that the sum of n over all test cases does not exceed 2000 (∑n≤2000).

Output
For each test case, print the answer — the maximum possible length of some subsequence of a that is a three blocks palindrome.

Example
Input
6
8
1 1 2 2 3 2 1 1
3
1 3 3
4
1 10 10 1
1
26
2
2 1
3
1 1 1
Output
7
2
4
1
1
3
思路:因为数字最大就到26,我们把每个数字出现的位置记录下来,然后暴力枚举1-26,对于枚举的每一个数字,两个指针前后一起动,然后寻找其余数中符合条件的数最多有多少个,不断的更新答案就可以了。寻找的过程用二分。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=2e3+100;
vector<int> p[30];
int n;

inline void init()
{
	for(int i=1;i<=26;i++) p[i].clear();
}
inline int fcs(int l,int r,int k)
{
	int _max=0;
	for(int i=1;i<=26;i++)
	{
		if(i==k) continue;
		int pos1=lower_bound(p[i].begin(),p[i].end(),l)-p[i].begin();
		int pos2=lower_bound(p[i].begin(),p[i].end(),r)-p[i].begin();
		pos2-=1;
		if(pos1>=r) continue;
		_max=max(_max,pos2-pos1+1);
	}
	return _max;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		init();int x;
		for(int i=1;i<=n;i++) 
		{
			scanf("%d",&x);
			p[x].push_back(i);
		}
		for(int i=1;i<=26;i++) sort(p[i].begin(),p[i].end());
		int _max=0;
		for(int i=1;i<=26;i++)
		{
			if(p[i].size()==0) continue;
			_max=max(_max,(int)p[i].size());
			int l=0,r=p[i].size()-1;
			while(l<r)
			{
				int len=fcs(p[i][l],p[i][r],i);
				_max=max(_max,(l+1)*2+len);
				l++,r--;
			}
		}
		printf("%d\n",_max);
	}
	return 0;
}

努力加油a啊,(o)/~

发布了668 篇原创文章 · 获赞 118 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/105541325