codeforce No to Palindromes!(枚举)

简介:

/*
     题意:给定一个字符串中没有任何长度>1的回文子串!求按照字典序的该串的下一个字符串
     也不包含长度>1的任何回文子串!
     
     思路:从最低位进行枚举,保证第i位 不与 第 i-1位和第 i-2位相同就好了!那么因为前边i-1
     位没有长度>1的回文子串,那么前i位也不会出现!最后将最后边的字符按照相同的原则补齐就好了! 
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;


char ch[1005];

int main(){
    int n, p;
    while(scanf("%d%d", &n,  &p)!=EOF){
        ch[0]='0';
        ch[1]='0';
        int up='a'+p-1;
        scanf("%s", ch+2);//从字符串第二位输入是因为第一位,第二位也要枚举 
        bool flag=false;
        for(int i=++n; i>=2 && !flag; --i){//枚举每一位 
            for(int j=ch[i]+1; j<=up && !flag; ++j){//每一位应该出现的字符(从小到大) 
                ch[i]=j;
                if(ch[i]!=ch[i-1] && ch[i]!=ch[i-2]){//保证三者互不相同 
                    flag=true;
                    for(int k=i+1; k<=n; ++k){//补全后面 
                        int cc;
                        for(cc='a'; cc<=up; ++cc)
                            if(cc!=ch[k-1] && cc!=ch[k-2]) break;
                        ch[k]=cc;
                    }
                }
            }
        } 
        if(flag) printf("%s\n", ch+2);
        else printf("NO\n");
    }
    return 0;
}

目录
相关文章
|
索引
LeetCode 336. Palindrome Pairs
给定一组唯一的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
123 0
LeetCode 336. Palindrome Pairs
codeforces446—— A.DZY Loves Sequences(DP+枚举)
codeforces446—— A.DZY Loves Sequences(DP+枚举)
84 0
codeforces446—— A.DZY Loves Sequences(DP+枚举)
|
人工智能 C++ Python
LeetCode 905. Sort Array By Parity
LeetCode 905. Sort Array By Parity
88 0
|
人工智能
Constant Palindrome Sum
Constant Palindrome Sum
Say No to Palindromes
题意: 给出一个字符串,长度为n,而且都是又a,b,c三个字符构成的,然后有m个询问 每个询问给出l r,问要想这个区间内不存在回文子串,至少要改多少个字符 结论: 一共会有六种情况
122 0
【LeetCode】Palindrome Pairs(336)
  Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a   palindrome.
106 0