B - Yet Another Palindrome Problem

B - Yet Another Palindrome Problem

 

 

 思路:

给一个长为n(5000≤5000)的数组,问是否存在一个长度至少为3的子序列是回文的。回文的定义是把序列reverse,序列不变,如[10,20,10]就是回文的。

考虑奇数长度的回文序列,删除其首尾元素仍然回文;再考虑偶数长度的回文序列,删除最中间那一对的某个元素,变成奇数长度的回文序列;因此原题等价于判断是否存在一个长度为3的子序列。for两遍就行。

代码:

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int a[5005], b[5005];

int fun(int n)
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n; j++)
        {
            if (b[a[j]])
                return 1;
        }
        b[a[i]] = 1;
    }
    return 0;
}

int main()
{
    int t, n;
    cin >> t;
    while (t--)
    {
        memset(b, 0, sizeof(b));
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> a[i];
        if (fun(n) == 1)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/pcdl/p/12499067.html