1289: arufuonsusnoufura
时间限制: 10 秒 内存限制: 128 MB
题目描述
爱德华有一天遇到了一个难题,他准备给弟弟送一个项链,不过炼金术师都有这么一个小爱好:喜欢对称,他希望买到的项链也是对称的,不过集市上左右对称的项链早就卖光了。聪明的爱德华准备随便买来一个自己取下几颗珍珠变成对称的。由于取下之后再安回去很麻烦,所以请你计算一下最少取下几枚珠子可以将其变为一个回文串(注意项链是个圈)。
输入
输入包含多组,第一行是T<=100,代表数据组数。
之后T行,每行包括一个字符串s,s中包含小写字母,大写字母和数字,分别代表不同颜色的珠子。s的长度2≤|S|≤200;
输出
对于每组等式,输出一行,每行1个数字,代表最少取下的珠子个数。
样例输入
5arufuonsusnoufuraAbcbasasasasasasastatistic6zc666
样例输出
02141
思路:
把环形转换成线性,枚举出所有字符串,对于每一个字符串求最大回文子串(LCS变形),就可解决。求最大回文子串时,可以转化成最少添加字符数使得该串变成回文串。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
char ch[210], str[210][210];
int dp[510][510];
int t, len;
int judge(char ss[]) { //最少添加字符数使得该串变成回文串
memset(dp, 0, sizeof(dp));
for(int i = 1; i < len; i++) {
for(int j = i; j < len; j++) {
int p = j - i;
if(ss[j] == ss[p]) dp[j][p] = dp[j - 1][p + 1];
else dp[j][p] = 1 + min(dp[j - 1][p], dp[j][p + 1]);
}
}
return dp[len - 1][0];
}
int main() {
scanf("%d", &t);
getchar();
while(t--) {
memset(str, 0, sizeof(str));
scanf("%s", ch);
len = strlen(ch);
int maxn, ans = 1e8;
for(int i = 0; i < len; i++) {
int cnt = len, ant = i, p = 0;
while(cnt--) {
str[i][p++] = ch[ant++];
if(ant == len) ant = 0;
}
maxn = judge(str[i]);
ans = min(ans, maxn);
}
printf("%d\n", ans);
}
return 0;
}