Codeforces Global Round 7 D2:Prefix-Suffix Palindrome (Hard version)

题意

给一个长度不超过1e6的字符串s,找一个回文串,回文串要求的条件是必须由a+b组成
a为s的前缀,b为s的后缀。(a,b都可以为空)

思路

首先可以把首尾相同的去掉,那么剩下中间一段,只需要找中间最长回文串,回文串开头为首位或者结束为末尾。可以用马拉车来处理,然后对其选取的进行标记

code

#pragma GCC optimize(2)
#include
using namespace std;
const int man = 2e6+10;
#define IOS ios::sync_with_stdio(0)
template <typename T>
inline T read(){T sum=0,fl=1;int ch=getchar();
for(;!isdigit(ch);ch=getchar())if(ch=='-')fl=-1;
for(;isdigit(ch);ch=getchar())sum=sum*10+ch-'0';
return sum*fl;}
template <typename T>
inline void write(T x) {static int sta[35];int top=0;
do{sta[top++]= x % 10, x /= 10;}while(x);
while (top) putchar(sta[--top] + 48);}
template<typename T>T gcd(T a, T b) {return b==0?a:gcd(b, a%b);}
template<typename T>T exgcd(T a,T b,T &g,T &x,T &y){if(!b){g = a,x = 1,y = 0;}
else {exgcd(b,a%b,g,y,x);y -= x*(a/b);}}
#ifndef ONLINE_JUDGE
#define debug(fmt, ...) {printf("debug ");printf(fmt,##__VA_ARGS__);puts("");}
#else
#define debug(fmt, ...)
#endif
typedef long long ll;
const ll mod = 1e9+7;
char str[man],tpstr[man];
int len[man],length;
bool vis[man];

void init(int l,int r){
    int id = 0;
    tpstr[id++] = '&';
    for(int i = l;i <= r;i++){
        tpstr[id++] = '#';
        tpstr[id++] = str[i];
    }
    tpstr[id++] = '#';
    tpstr[id] = 0;
    length = id;
}

void manacher(int l,int r){
    init(l,r);
    int mx = 0,id = 0;
    len[0] = 1;
    for(int i = 1;i < length;i++){
        len[i] = mx > i ? min(mx-i,len[2*id-i]) : 1;
        while(tpstr[i-len[i]]==tpstr[i+len[i]])len[i]++;
        if(i+len[i]>mx){
            mx = i + len[i];
            id = i;
        }
    }
    int maxlen = 0,ans_l = 0,ans_r = 0;
    for(int i = 1;i < length;i++){
        int tplen = len[i] - 1;
        if(i - len[i] == 0){
            if(maxlen<tplen){
                maxlen = tplen;
                ans_l = l;
                ans_r = l + (len[i] - 1) - 1;
            }
        }
        if(i + len[i] == length){
            if(maxlen<tplen){
                maxlen = tplen;
                ans_r = r;
                ans_l = r - (len[i] - 1) + 1;
            }
        }
    }
    for(int i = ans_l;i <= ans_r;i++){
        vis[i] = 1;
    }
}

int main() {
    #ifndef ONLINE_JUDGE
        //freopen("in.txt", "r", stdin);
        //freopen("out.txt","w",stdout);
    #endif
    int t;
    cin >> t;
    while(t--){
        cin >> str + 1;
       // memset(vis,0,sizeof(vis));
        int len = strlen(str+1);
        int l = 1,r = len;
        while(l<=r&&str[l]==str[r]){
            vis[l] = vis[r] = 1;
            l++;r--;
        }
        if(l>=r){
            cout << str + 1 << endl;
            memset(vis,0,sizeof(int)*(len+5));
            continue;
        }
        manacher(l,r);
        for(int i = 1;i <= len;i++){
            if(vis[i]){
                vis[i] = 0;
                cout << str[i];
            }
        }cout << endl;
    }   
    return 0;
}

你可能感兴趣的:(codeforce,思维,字符串)