Paul hates palindromes. He assumes that strings is tolerable if each its character is one of the firstp letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.
Paul has found a tolerable string s of lengthn. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
The first line contains two space-separated integers: n andp (1 ≤ n ≤ 1000;1 ≤ p ≤ 26). The second line contains strings, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
3 3 cba
NO
3 4 cba
cbd
4 4 abcd
abda
String s is lexicographically larger (or simply larger) than stringt with the same length, if there is numberi, 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.
题目大意:
给你一个长度为N的串,其中只包含前p个英文字母,保证输入的是一个子序列中没有长度为2或者是长度大于2的回文串。
让你找到一个比原字符串字典序大的第一个也满足:子序列中没有长度为2或者是长度大于2的回文串的解。如果不存在,输出NO。
思路:
1、好菜啊T T又看题解辣T T,思路来源:http://blog.csdn.net/keshuai19940722/article/details/39137373
2、如果一个字符串没有长度为2的子回文串,那么就能保证整个字符串是没有两个相邻的字符相同的。
同理,如果一个字符串没有长度为3的子回文串,那么就能保证整个字符串没有两个间隔一个字符的两个字符是相同的。
那么换句话说,综上两点,就是在说没有任意三个相邻的字符是相同的,只要满足这一点,那么这个字符串一定是一个可行串。
3、那么我们从最后边开始暴力处理:
①如果当前位子<0,那么说明不存在可行解,如果当前位子==n,那么说明存在解。
②对应当前位子的字符字典序+1,判断一下当前位子和前边两个位子的字符是否相等,如果存在相等,说明当前解不可行,继续字典序+1.
如果不存在相等,那么当前位子是一个可行解,将位子向后移一位。
③若在过程②中,当前位子的字符字典序加到了p还是不可行,那么我们将位子向前移一位,去处理之前为可行之后,再回到这个位子重新暴力处理。
Ac代码:
#include<stdio.h>
#include<string.h>
using namespace std;
char a[10005];
int judge(int pos)
{
if(pos>=1&&a[pos-1]==a[pos])return 0;
if(pos>=2&&a[pos-2]==a[pos])return 0;
return 1;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
scanf("%s",a);
int pos=n-1;
while(1)
{
if(pos==n)
{
printf("%s\n",a);break;
}
if(pos<0)
{
printf("NO\n");break;
}
if(a[pos]-'a'+1==m)
{
a[pos]='a'-1;
pos--;
}
else
{
int tmp=(a[pos]-'a'+1)%m;
a[pos]='a'+tmp;
if(judge(pos)==1)pos++;
}
}
}
}