设为首页 加入收藏

TOP

Codeforces Round #265 (Div. 2) C. No to Palindromes!(字符串+构造??)
2015-07-20 17:44:10 来源: 作者: 【 】 浏览:2
Tags:Codeforces Round #265 Div. Palindromes 字符串 构造

C. No to Palindromes! time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output

Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and sdoesn't contain any palindrome contiguous substring of length 2 or more.

Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.

Input

The first line contains two space-separated integers: n and p (1?≤?n?≤?1000; 1?≤?p?≤?26). The second line contains string s, consisting of nsmall English letters. It is guaranteed that the string is tolerable (according to the above definition).

Output

If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).

Sample test(s) input
3 3
cba
output
NO
input
3 4
cba
output
cbd
input
4 4
abcd
output
abda
Note

String s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1?=?t1, ..., si?=?ti, si?+?1?>?ti?+?1.

The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.

A palindrome is a string that reads the same forward or reversed.


题意给出一个由字母表的前p个字符构成的长度为n的串,该串的子串中不存在长度大于等于2的回文,要你求下一个字典序比这这个串大且满足串中不存在长度大于等于2的回文子串的串.(串的长度和原串等长)思路,因为字典序比这个串大,所以只需要增加该串的某个位置,然后这个位置后面的构造字典序最小的字符串,代码如下


#include
  
   
#include
   
     #include
    
      #include
     
       #include
       using namespace std; int n,p; char s[1005],ans[1005]; int main() { ios_base::sync_with_stdio(false); while(cin>>n>>p) { cin>>s; int L=strlen(s); bool ok=false; for(int j=L-1; j>=0; j--) { for(int i=1; s[j]+i<'a'+p; i++) { char tmp=s[j]+i; if(j>=2&&(tmp==s[j-1]||tmp==s[j-2]))continue; if(j==1&&tmp==s[j-1])continue; int k=j+1; s[j]=tmp; if(j==L-1){ok=true;break;} while(k
       
        1&&s[k-2]-'a'==c)continue; s[k]=c+'a'; if(k==L-1)ok=true; break; } k++; } if(ok)break; } if(ok)break; } if(ok)puts(s); else puts("NO"); } return 0; }
       
     
    
   
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇LeetCode 第九题, Palindrome Num.. 下一篇zoj 3818 Pretty Poem (模拟)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)