codeforce No to Palindromes!(枚举)

 1 /*
 2      题意:给定一个字符串中没有任何长度>1的回文子串!求按照字典序的该串的下一个字符串
 3      也不包含长度>1的任何回文子串!
 4      
 5      思路:从最低位进行枚举,保证第i位 不与 第 i-1位和第 i-2位相同就好了!那么因为前边i-1
 6      位没有长度>1的回文子串,那么前i位也不会出现!最后将最后边的字符按照相同的原则补齐就好了! 
 7 */
 8 #include<iostream>
 9 #include<cstdio>
10 #include<cstring>
11 #include<algorithm>
12 
13 using namespace std;
14 
15 
16 char ch[1005];
17 
18 int main(){
19     int n, p;
20     while(scanf("%d%d", &n,  &p)!=EOF){
21         ch[0]='0';
22         ch[1]='0';
23         int up='a'+p-1;
24         scanf("%s", ch+2);//从字符串第二位输入是因为第一位,第二位也要枚举 
25         bool flag=false;
26         for(int i=++n; i>=2 && !flag; --i){//枚举每一位 
27             for(int j=ch[i]+1; j<=up && !flag; ++j){//每一位应该出现的字符(从小到大) 
28                 ch[i]=j;
29                 if(ch[i]!=ch[i-1] && ch[i]!=ch[i-2]){//保证三者互不相同 
30                     flag=true;
31                     for(int k=i+1; k<=n; ++k){//补全后面 
32                         int cc;
33                         for(cc='a'; cc<=up; ++cc)
34                             if(cc!=ch[k-1] && cc!=ch[k-2]) break;
35                         ch[k]=cc;
36                     }
37                 }
38             }
39         } 
40         if(flag) printf("%s\n", ch+2);
41         else printf("NO\n");
42     }
43     return 0;
44 } 

 

posted @ 2014-09-10 16:43  hjzqyx  阅读(343)  评论(0编辑  收藏  举报