题解:P13790 「CZOI-R6」Border

· · 题解

Idea

字符串的长度为 n,将答案从 n-1 到 1 枚举,如果符合要求直接输出就行了。

输入的字符串是 a,假设 a_i 对应的是 a_j,很明显的,如果 a_i=a_j,可以直接跳过。

但如果 a_i \ne a_j,就需要分情况讨论了。

这里假设后缀的开始坐标为 st。

如果 i \ge st,那么 a_i 不能轻易改动,因为如果将 a_i 改为 a_j,那么 a_i 与 a_{i-st+1} 的关系就会矛盾;显然,只能改变 a_j,但如果 j \le n-st+1,也就是 j 在 a 当前的前缀上,还需要考虑 a_j 与 a_{st-1+j} 的关系。

上面一大堆只是一种情况,还有很多种情况,这里就不一一说了,有兴趣的可以自己想想。

Code

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
char a[N];
int main(){

    cin>>a+1;
    int n=strlen(a+1);
    if(n==1){ //特判,不多说了 
        cout<<0;
        return 0;
    }else if(n==2){
        cout<<1;
        return 0;
    }
    for(int i=n-1;i>=1;i--){ //枚举答案 
        int st=n-i,cnt=0,cnt2=0;
        int bj=0; //一定要赋值为 0 
        char x;
        for(int j=1;j<=i;j++){
            if(a[j]!=a[st+j]){
                if(cnt){ //已经修改过一次了 
                    cnt2=1;
                    break;
                }else{
                    cnt=1;
                    if(j>=st+1){ //这是我上文讲的情况 
                        if(i<st+j){
                            bj=st+j;
                            x=a[bj];
                            a[st+j]=a[j];                       
                        }else{
                            if(a[n-i+st+j]==a[j]){
                                bj=st+j;
                                x=a[bj];
                                a[st+j]=a[j];
                            }else{
                                cnt2=1;
                                break;
                            }
                        }
                    }else if(j<st+1&&i>=st+j){ //这是另一种 
                        //n-(i-(st+j))
                        if(a[n-i+st+j]==a[st+j]){
                            bj=j;
                            x=a[bj];
                            a[j]=a[st+j];
                        }else if(a[n-i+st+j]==a[j]){
                            bj=st+j;
                            x=a[bj];
                            a[st+j]=a[j];
                        }else{
                            cnt2=1;
                            break;
                        }
                    }else if(i<st+1){ //这是另一种 
                        bj=st+j;
                        x=a[bj];
                        a[st+j]=a[j];
                    }else if(j<st+1&&i<st+j){ //这是另一种 
                        bj=st+j;
                        x=a[bj];
                        a[st+j]=a[j];
                    }
                }
            }
        }
        if(cnt2==0){
            cout<<i;
            return 0;
        }
        if(cnt){
            a[bj]=x;
        }
    }

    return 0;
}