Codeforces Round #265 (Div. 2) C. No to Palindromes!

來源:互聯網
上載者:User

標籤:style   io   os   ar   for   div   sp   cti   on   

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.

Input

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).

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 3cba
Output
NO
Input
3 4cba
Output
cbd
Input
4 4abcd
Output
abda
Note

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.

題意:求滿足大於給定串的序列,而且兩個序列都不包含長度大於等於2的迴文子串

思路:首先,因為不能有長度大於等於2的子串,所以當前位置是不能和它的前一個和前第二個一樣的。因為給定串也是不包含迴文子串的,所以為了能找個一個最小的滿足條件的字串,我們從右往前改,找到一個滿足不與前兩個一樣的位置的話,那麼從這個位置往右就是填寫不構成迴文的最小串了

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1010;int n, p;char str[maxn], tmp;int find(const int &x) {if (x == -1) return 0;for (int i = 1; ; i++) {if (str[x] + i >= tmp) break;if (x > 0 && str[x-1] == str[x] + i) continue;if (x > 0 && str[x-2] == str[x] + i) continue;str[x] += i;return 1;}if (!find(x-1)) return 0;str[x] = 'a';for (int i = 0; ; i++) {if (str[x] + i >= tmp) break;if (x > 0 && str[x-1] == str[x] + i) continue;if (x > 1 && str[x-2] == str[x] + i) continue;str[x] += i;return 1;}return 0;}int main() {scanf("%d%d", &n, &p);tmp = 'a' + p;scanf("%s", str);if (find(n-1))printf("%s\n", str);else printf("NO\n");return 0;}


Codeforces Round #265 (Div. 2) C. No to Palindromes!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.