Codeforce 464A. No to Palindromes!

A. 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 = tisi + 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.

题目要求了 一个串任何子串都是非回文串,很容易想得到只要 一个串第 i 个位置与 i - 1 与 i - 2 都不相同的话 ,就符合条件了 。

然后题目要求 构造一个字典序大于给出的串的合法串,并且字典序尽量少 。

当时做的时候老想着从后向前扫,得到的必定最少,这样的想法有问题,因为后面的字符更改了再改前面的字符这样是存在后效性的 。 

正确的做法是从前向后面开始扫 ,然后就是记录一下前面是否对串进行过更改 , 这样就可以得到正解了 ~

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1010;
int n , m;
char s[N],ans[N];
int tag =0 ;

bool solve( int pos , int flag )
{
    int i ;
    if(pos == n) {
        return 1 ;
    }
    if( flag )
        i = 0 ;
    else {
        i = s[pos] ;
        if( pos == n - 1 ) i++;
    }

    for( ; i < m ; ++i ){
        if(  ( pos > 0 && i == ans[ pos-1 ] ) || ( pos > 1 && i == ans[pos - 2 ]) )continue;
        ans[pos] = i ;
        if( i > s[pos] )flag = 1;
        if( solve ( pos+1 , flag) )return 1;
    }
    return  0;
}

int main()
{
    #ifdef  LOCAL
        freopen("in.txt","r",stdin);
    #endif

    while( cin>>n>>m ){
        scanf("%s",s);
        for(int i = 0 ; i < n ; ++i ){
            s[i] -= 'a';
        }
        if( !solve( 0 , 0 ) ){
            cout<<"NO";
        }
        else {
            for(int i = 0 ;i < n ; ++i)
                cout<< (char) (ans[i] + 'a');
        }
        cout<<endl;
    }
    return 0;
}
only strive for your goal , can you make your dream come true ?
原文地址:https://www.cnblogs.com/hlmark/p/3962736.html