HDU5340-Three Palindromes

本文探讨了一个字符串能否被划分为三个非空回文子串的问题,并提供了一种使用Manacher算法进行求解的方法。

Three Palindromes

                                                                  Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
                                                                                          Total Submission(s): 1728    Accepted Submission(s): 611


Problem Description
Can we divided a given string S into three nonempty palindromes?
 

Input
First line contains a single integer  T20  which denotes the number of test cases.

For each test case , there is an single line contains a string S which only consist of lowercase English letters. 1|s|20000
 

Output
For each case, output the "Yes" or "No" in a single line.
 

Sample Input
  
2 abc abaadada
 

Sample Output
  
Yes No
 

Source
 

Recommend
hujie
 

题意:给你一个字符串,问能不能分为三个回文子串

解题思路:用Manachar计算以每个字符为中心的最长回文串长度,然后枚举头尾的回文串,判断中心是否为回文串


#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>

using namespace std;

#define LL long long
const int INF = 0x3f3f3f3f;

char s1[20009], s2[40009];
int p[40009];
int a[40009], b[40009];

int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		scanf("%s", s1);
		s2[0] = '$';
		int len = 1, i = 0;
		while (s1[i])
		{
			s2[len++] = '#';
			s2[len++] = s1[i++];
		}
		s2[len++] = '#';
		s2[len] = '\0';
		memset(p, 0, sizeof p);
		int id = 0, ma = 0;
		for (int i = 0; i < len; i++)
		{
			p[i] = ma > i ? min(p[id * 2 - i], ma - i) : 1;
			while (s2[i + p[i]] == s2[i - p[i]]) p[i]++;
			if (i + p[i] > ma)
			{
				ma = i + p[i];
				id = i;
			}
		}
		int cnt1 = 0, cnt2 = 0;
		for (int i = 2; i < len - 1; i++)
		{
			if (p[i] == i) a[cnt1++] = i;
			if (p[i] == len - i) b[cnt2++] = i;
		}
		int flag = 0;
		for (int i = 0; i < cnt1; i++)
		{
			for (int j = 0; j < cnt2; j++)
			{
				int l = a[i] + p[a[i]];
				int r = b[j] - p[b[j]];
				int mid = (l + r) >> 1;
				if (l > r || (l == r&&s2[mid] == '#')) continue;
				if (p[a[i]] * 2 - 1 + p[mid] * 2 - 1 + p[b[j]] * 2 - 1 >= len - 1) {flag = 1; break;}
			}
			if (flag) break;
		}
		if (flag) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值