A. No to Palindromes! (Thinking + Simulation)

https://codeforces.com/problemset/problem/464/A


 

Ideas:

If a string has no sub-palindromic string of length 2, then it can be guaranteed that no two adjacent characters are the same in the entire string.

In the same way, if a string does not have a sub-palindromic string of length 3, then it can be guaranteed that no two characters separated by one character are the same in the entire string.

Therefore, no three adjacent characters are the same, as long as this is satisfied, then this string must be a feasible string.

Code:

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=1e3+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
char s[maxn],b[maxn];
bool judge(char str[],LL i,LL j,LL k){
    if(str[i]==str[j]||str[i]==str[k]||str[j]==str[k]) return false;
    else return true;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n,p;cin>>n>>p;
  cin>>(s+1);
  for(LL i=1;i<=n;i++) b[i]=s[i];
  if(n==1){
    bool flag=1;
    if(s[1]=='z'||('a'+p-1)<=s[1]) cout<<"NO"<<"\n";
    else cout<<char(s[1]+1)<<"\n";
    return 0;
  }
  /*if(n==2){
    bool flag=1;
    for(LL i=n;i>=1;i--){
        for(char j=s[i]+1;j<='a'+p-1;j++){
            b[i]=j;
            if(judge(i-1,i)==true)}{
                flag=0;
                for(LL )
            }
        }
    }
    if(flag==0) cout<<"NO"<<"\n";
    else for(LL i=1;i<=n;i++) cout<<b[i];
    return 0;
  }*/
  bool flag=1;
  for(LL i=n;i>=1;i--){

     for(char j=s[i]+1;j<='a'+p-1;j++){
        b[i]=j;

        if(i<2||judge(b,i-2,i-1,i)==true){
            flag=0;
            if(i==n){

                for(char u=s[i]+1;u<='a'+p-1;u++){
                    b[n]=u;
                    if(judge(b,n-2,n-1,n)==true) break;
                }
            }
            else{
                for(LL k=i+1;k<=n;k++){
                    for(char u='a';u<='a'+p-1;u++){
                        b[k]=u;
                        if(judge(b,k-2,k-1,k)==true) break;
                    }
                }
            }
        }
        if(flag==0) break;
        b[i]=s[i];
    }
    if(flag==0) break;
  }
  if(1==flag){
    cout<<"NO"<<"\n";
  }
  else{
    for(LL i=1;i<=n;i++) cout<<b[i];
  }
return 0;
}

 

Guess you like

Origin blog.csdn.net/zstuyyyyccccbbbb/article/details/114677506