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.
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).
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 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.
第一次做出来C题, 但还觉得有所思, , 应该归于 模拟类的吧 ;
题解 : 对于每一个字母, 只需判断他与之前两个字母是否合法就行 ,
比赛后, 调试简化的代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>`
#include <algorithm>
#include <cctype>
#include <queue>
#include <vector>
#define INF 100000000 //0x7fffffff
#define eps (1e-9)
#define clearto(s,x) memset(s,x,sizeof(s))
using namespace std;
int n,m,p;
char st[1100],ans[1100];
int check(int id){
st[id]++; int c =st[id]-96;
while(c<=p){
if(st[id]!=st[id-1] && st[id]!=st[id-2])
{ return 1; } st[id]++; c++ ;
}
return 0;
}
int main()
{
//freopen("D:\data.txt","r",stdin);
int TT,t =0,i,k; int ok =0,flag=1;
scanf("%d %d",&n,&p); getchar(); scanf("%s",st); //printf("%s\n",st);
//------------------
if(n==1){
if(st[0]-96<p) printf("%c",st[0]+1);
else printf("NO"); return 0;
}
if(n>2&&check(n-1)) { printf("%s",st); return 0; }
//------------------
int id =n-2;
while(id>=2){
if(check(id)==0){ id--; continue; } //printf("%d %c %s\n",id,st[id],st);
for(i=id+1;i<n;i++)
{ st[i]=96; check(i); }
ok =1; id=0;//或 break;
}
if(ok) { printf("%s",st); return 0; }
//------------------
flag=0;
if(st[1]-96<p)
{
st[1]++; flag=1;
if(st[1]==st[0]){
flag=0;
if(st[1]-96<p) { st[1]++; flag=1; }
else if(st[0]-96<p) { st[1]=st[0]; st[0]++; flag=1; }
}
}
else if(st[1]-96==p&&st[0]-96<p)
{ st[0]++; st[1]=97; flag=1; }
if(flag==0){ printf("NO"); return 0; }
for(i=2;i<n;i++)
{ st[i]=96; check(i); }
if(flag){ printf("%s",st); return 0; }
//-------------------
printf("NO");
return 0;
}