Palindrome Names

来源:互联网 发布:数据之魅 编辑:程序博客网 时间:2024/06/05 00:57

Anna and Bob are having a baby. They both enjoy the advantage of having palindrome names, meaning that their names are spelled the same way forwards and backwards. Wanting to be good parents, they decide to give their child a palindrome name too. The only problem is that they aren’t sure if the one they picked is a palindrome. If it turns out it isn’t a palindrome, they want to change it to a palindrome using as few changes as possible. The allowed changes are:

  • Change one letter of the name.

  • Add a letter to the end of the name.

Help Bob and Anna find out how many changes they need to make to the name to make it a palindrome.

Input

Input is the name they have chosen.

Output

Output the number of changes they need to make.

Limits

  • The length of the name is at least 11 and at most 100100 characters.

  • The name consists of only lowercase letters a–z.

Sample Input 1Sample Output 1
kaia
1

Sample Input 2Sample Output 2

abcdefgded
4


这道题,一开始我是分类讨论的,正序和反序相比,看第一个字母是否相等,来判断是添加字母,还是修改字母,后来试了很多次,发现这样过不了一些特殊的例子。后来看了刘题勇的代码,才发现,也是暴力,方法有点像,在处理上有不同。

我就演示一下第一组数据吧

#include <iostream>#include <cstring>#include <cstdio>using namespace std;int main(){    char ch[105];    while(scanf("%s",ch)!=EOF)    {        int l,s=10000,sum;        l=strlen(ch);        for (int t=0;t<l;t++)        {            int x1,x2;            x1=t;            x2=l-1;            sum=t;            while(x1<l)            {                if (ch[x1]!=ch[x2]&&x1<x2) sum++;                x1++;                x2--;            }            if (sum<s) s=sum;        }        printf("%d\n",s);    }    return 0;}

 t=0,sum=0;

    kaia

    aiak      有4个字母不同  sum=4  s=4;

 t=1,sum=1;

   kaia

    aiak     没有字母不同,但是k要添加,所以sum=1+0=1;s=1;

 此时答案已经出来了,但是还是要暴力走完它

t=2,sum=2;

  kaia

     aiak   sum=2+2=4;s=1;

t=3,sum=3;

  kaia

       aiak   sum=3+0=3;s=1;

  break;

答案就是1,这想法在暴力找最优解。想法有点妙。

原创粉丝点击