题解 P2799 【国王的魔镜】

斯德哥尔摩

2017-09-24 20:48:01

Solution

虽然这一道水题我第一次就写对了。。。 然而还是有必要写一篇 题解 让那些刚入门(坑)的同学看一看,学递归。 附注释的代码: ```cpp #include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; int n; char a[100010]; bool check(int x){//判断是否是左右对称 for(int i=1;i<=x/2;i++)if(a[i]!=a[x-i+1])return true;//拆成两半,对比,若不是左右对称,返回 true return false; } void work(int x){ if(x%2){//如果长度为奇数,则 打印出答案 并 跳出递归 ,当然有可能用不到,不过还是加上的好。。。 printf("%d\n",x); return; } if(check(x)){//如果不是左右对称,则 打印出答案 并 跳出递归 printf("%d\n",x); return; } else work(x/2);//否则 拆成两半 继续递归 } int main(){ scanf("%s",a+1);//习惯下标从 1 开始 n=strlen(a+1);//字符长度 work(n); return 0; } ```