codeforces C. No to Palindromes!

http://codeforces.com/contest/465/problem/C

题意:给你一个字符串,然后按照字典序找出下一个字符串,这个字符串中不能含有长度大于等于2的子串为回文串,如果含有输出,否则输出NO;

思路:判断回文串时只需判断要修改的i位置,i+1位置和i+2位置是不是与这个要修改的字符相等。字符串的前缀不含有回文子字符串,改变i位后也不会含有。

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <queue>
 6 #include <map>
 7 #include <algorithm>
 8 #define maxn 1000010
 9 #define ll long long
10 using namespace std;
11 const int inf=1<<30;
12 
13 int n,p;
14 char str[maxn];
15 char s1[maxn];
16 
17 
18 int main()
19 {
20      scanf("%d%d",&n,&p);
21      scanf("%s",str);
22      strcpy(s1,str);
23      bool flag=false;
24      for(int i=n-1; i>=0; i--)
25      {
26          for(int j=(str[i]-'a')+1; j<p; j++)
27          {
28               char ch='a'+j;
29               if(str[max(i-1,0)]==ch||str[max(i-2,0)]==ch)
30               {
31                   continue;
32               }
33               str[i]=ch;
34               flag=true;
35               break;
36          }
37          if(flag)
38          {
39              for(int j=i+1; j<n; j++)
40              {
41                  for(int k=0; k<p; k++)
42                  {
43                       if((j-1>=0&&str[j-1]=='a'+k)||(j-2>=0&&str[j-2]=='a'+k))
44                       {
45                           continue;
46                       }
47                       str[j]='a'+k;
48                       break;
49                  }
50              }
51              if(strcmp(s1,str)!=0)
52              {
53                  printf("%s
",str);
54                  return 0;
55              }
56          }
57      }
58      printf("NO
");
59      return 0;
60 }
View Code
原文地址:https://www.cnblogs.com/fanminghui/p/4350989.html