一个字符串是非回文的,当且仅当,他只由前p个小写字母构成,而且他不包含长度大于等于2的回文子串。
给出长度为n的非回文串s。请找出字典序比s大的,而且字典序要最小的长度为n的非回文。
Input
单组测试数据。 第一行有两个整数n 和p (1≤n≤1000; 1≤p≤26)。 第二行包含一个字符串s,它的长度是n。输入保证他是非回文的。
Output
输出字典序比s大的且字典序要最小的长度为n的非回文,如果不存在输出NO。
Input示例
样例输入1 3 3 cba 样例输入2 3 4 cba
Output示例
样例输出1 NO 样例输出2 cbd#include <iostream> #include <cstring> using namespace std; char input[1001]; int n, p; bool check(int index) { if (index > 0 && input[index] == input[index-1]) { return false; } if (index > 1 && input[index] == input[index-2]) { return false; } return true; } bool fun(int index) { while (true) { if (index >= n) { return true; } if (index < 0) { return false; } if (input[index] == 'a' + p - 1) { input[index] = 'a' - 1; index--; } else { int k = (input[index]+1-'a')%p; input[index] = 'a' + k; if (check(index)) { index++; } } } } int main() { cin >> n >> p; cin >> input; if (fun(n-1)) { cout << input << endl; } else { cout << "NO" << endl; } return 0; }