1324B. Yet Another Palindrome Problem
回顾人生第二场 cf(还是div.3),如今看来仍然是惨不忍睹,能被1100的题卡住
Description
Analysis
题意概述
t t t 组测试数据,每组给出一个长度为 n n n 的序列( 3 ≤ n ≤ 5000 3\le n\le 5000 3≤n≤5000),判断当前序列是否存在长度 ≥ 3 \ge 3 ≥3 的回文子序列
分析
回文子序列不等同于子串,考虑回文子序列的长度特点:
对于所有长度大于 3 3 3 的回文子序列, e g : 1 , 1 , 2 , 3 , 2 , 1 , 1 eg:1,1,2,3,2,1,1 eg:1,1,2,3,2,1,1,其自身一定包含长度为 3 3 3 的回文子序列:
(构造方法:保留首尾的两个数,中间任意保留一个数)
因此,只需记录序列中每个元素首次出现的位置,判断其之后重复出现的位置与首次出现的位置之差 ≥ 2 \ge 2 ≥2 即可
时间复杂度: O ( n ) O(n) O(n)
Code
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
constexpr const int N = 1e6 + 10;
int a[N], p[N], n, t;
int main()
{
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
cin >> t;
while(t--)
{
bool f = 0;
memset(p, 0, sizeof p);
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i];
if(!p[a[i]]) p[a[i]] = i;
else if(!f && p[a[i]])
if(i - p[a[i]] >= 2) f = 1;
}
if(f) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}
Tag
字符串:子序列(性质分析)+回文