No to Palindromes! CodeForces - 464A
原题链接
考察:贪心(?)
思路:
不存在回文子串的条件是对于任意\(i\),均有:
\[s[i]!=s[i-1] , s[i] != s[i-2]
\]
DFS枚举每一个修改的值.
Code
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010;
char s[N],b[N];
int n,p;
bool dfs(int u,bool limit)
{
if(u>n)
{
memcpy(b,s,sizeof s);
return 1;
}
char t = s[u];
char st = limit?s[u]:'a';
if(u==n&&st==t) st++;
for(char c=st;c<='a'+p-1;c++)
{
s[u] = c;
if(u>=1&&s[u-1]==s[u]) continue;
if(u>=2&&s[u-2]==s[u]) continue;
if(dfs(u+1,limit&&c==t)) return 1;
s[u] = t;
}
return 0;
}
int main()
{
scanf("%d%d%s",&n,&p,s+1);
if(dfs(1,1)) printf("%s\n",b+1);
else puts("NO");
return 0;
}