首页 > 代码库 > Light OJ 1258 Making Huge Palindromes 末尾添加最少字符变回文串

Light OJ 1258 Making Huge Palindromes 末尾添加最少字符变回文串

题目来源:Light OJ 1258 Making Huge Palindromes

题意:末尾添加最少的字符是使输入的串变成回文 输出长度

思路:直接KMP匹配出它和它反串的最大匹配 n减去它就是要添加的数量

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1000010;
char a[maxn], p[maxn];
int f[maxn];
void getFail()
{
	int m = strlen(p);
	f[0] = f[1] = 0;
	for(int i = 1; i < m; i++)
	{
		int j = f[i];
		while(j && p[i] != p[j])
			j = f[j];
		f[i+1] = p[i] == p[j] ? j+1 : 0;
	}
}
int find()
{
	int cnt = 0;
	int j = 0;
	int n = strlen(a);
	int m = strlen(p);
	for(int i = 0; i < n; i++)
	{
		while(j && a[i] != p[j])
			j = f[j];
		if(a[i] == p[j])
			j++;
	}
	return j;
}

int main()
{
	int cas = 0; 
	int T;
	scanf("%d", &T); 
	while(T--)
	{
		scanf("%s", a);
		int n = strlen(a);
		p[n] = 0;
		for(int i = 0; i < n; i++)
			p[i] = a[n-i-1];
		getFail();
		printf("Case %d: %d\n", ++cas, 2*n-find());
	}
	return 0;
}