CF 464 A No to Palindromes! 找到最后靠后的可变字母;

本文介绍了一个算法挑战,任务是找出给定长度和字符集限制下,字典序上紧接给定字符串之后的下一个不含回文子串的字符串。文章详细解释了问题背景、输入输出要求,并提供了一个实现思路及代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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 ands doesn'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 ≤ 10001 ≤ p ≤ 26). The second line contains string s, consisting of n small 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.


/*  
先从后向前遍历一遍;每个位子,从当前字母慢慢增加,直到找到和前面两个字母均不同的一个字母,且不能超过限制m;
变化的是尽可能后面的字母,从而保证结果出来的字典序最小;
找到即是有答案;
因为原来的是没回文的。 那么把找到后一个的字母从a开始遍历一遍,
从最左边开始,从而保证结果字典序最小;
*/  
#include<stdio.h>
int n,m;
char a[2000];
bool judge(char ch,int i)
{
	for(;ch<'a'+m;ch++)
	{
		if((i==0||ch!=a[i-1])&&(i<=1||ch!=a[i-2]))
		{
			a[i]=ch;
			return 1;
		}
		
	}
	return 0;
}
void get(int i)
{
	for(i++;i<n;i++)
	{
		for(a[i]='a';a[i]<'a'+m;a[i]++)
		{
			if((a[i]!=a[i-1]||i==0)&&(i<=1||a[i]!=a[i-2]))
				break;
		}
	}
}
	
int main()
{
	int ok,i;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		scanf("%s",a);
		ok=-1;
		for(i=n-1;i>=0;i--)
		{
			if(judge(a[i]+1,i))
			{
				ok=i;
				break;
			}
		}
		if(ok!=-1)
		{
			get(ok);
			puts(a);
		}
		else
		{
			puts("NO");
		}
	}
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值