题意
给一堆长度小于等3的字符串,如果过程中能任意跳过字符串,是否存在一种方案让剩余的字符串为回文串。
题解
可以证明只需要考虑两个字符串片段能否组成一个回文串片段即可。假设有一个字符串是由三个以上片段组成,我们来考虑它的长度组合?首先如果一个字符串长度为1那它自回文所以不考虑。那么三个字符串可能为,3 3 3,3 3 2,3 2 3,3 2 2 ,2 3 3,2 2 2,2 2 3.假如这个字符串回文,我们可以发现把中间一个回文串去掉,剩下的字符串也可也回文,所以我们只需要考虑两个字符串是否能够组成回文串即可。那么所有可能的组合情况是 1,2,3,2 2,3 3,2 3,3 2.
1 2 3 和2 2 ,3 3可以自回文和简单逆串回文,这里需要主义的是长度为3的前缀也可也加入集合,在2 3,3 2的组合中需要区分一下。避免出现2(假)3的情况。如abc dba。
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const int N = 2e5 + 10;
int solve()
{
int n; cin >> n;
map<string,int>s;
int flag=0;
for (int i = 1; i <= n; i++)
{
string a;
cin >> a;
if (flag)continue;
if (a.size() == 1 || a[0] == a[a.size() - 1])flag=1;
if (a.size() == 2)
{
string t = a;
reverse(t.begin(), t.end());
if (s.count(t))flag= 1;
s[a] = 2;
}
if (a.size() == 3)
{
string pre = a.substr(0, 2), nx = a.substr(1), yuan = a;
reverse(nx.begin(), nx.end());
reverse(yuan.begin(), yuan.end());
if (s.count(nx)&&s[nx]==2)flag = 1;
if (s.count(yuan))flag = 1;
s[a.substr(0, 2)] = 3,s[a]=3;
}
}
return flag;
}
int main()
{
int t;
cin >> t;
while (t--)
{
if (solve())cout << "YES" << endl;
else cout << "NO" << endl;
}
}