题目:http://codeforces.com/contest/505/problem/A
题意分析:1.字符串全为小写,长度不超过10 2.允许在字符串任意位置插入一个小写字母,判断是否能够变为回文串。 如果能, 输出该串。 不能, 输出 ‘NA’
MA:实在想不出什么好的优化算法, 只好暴力了~~ 思路是遍历每个位置,把字符串数组存到另一数组中,每次并空出一位, 枚举26个字母(其实可以只枚举原串中的就足够)直到变为回文串~~~ 真的是好粗暴。。
#include <cstring>
#include <cstdio>
const int maxn = 20 + 10;
char s[maxn], b[maxn];
int is_p(int n)
{
for(int i = 0, j = n-1; i <= j; i++, j--) if(b[i] != b[j]) return 0;
return 1;
}
int solve()
{
int n = strlen(s);
memset(b, 0, sizeof(b));
for(int i = 0; i <= n; i++)
{
for(int j = 0; j < i; j++) b[j] = s[j];
for(int j = i; j < n; j++) b[j+1] = s[j];
for(char k = 'a'; k <= 'z'; k++)
{
b[i] = k;
if(is_p(n+1))
{
printf("%s\n", b);
return 1;
}
}
}
return 0;
}
int main()
{
while(~scanf("%s", s))
{
if(!solve()) printf("NA\n");
memset(s, 0, sizeof(s));
}
return 0;
}
本文解析了CodeForces竞赛中一道关于字符串处理的问题——如何通过插入一个字符将字符串转换成回文串。介绍了题目的要求及限制条件,并提供了一个简单的C++实现方案。
432

被折叠的 条评论
为什么被折叠?



