头部背景图片
Decaku 's Blog |
Decaku 's Blog |

CF Codeforces Global Round 7 D2

$有一个字符串S,找到S的一个不重叠前缀和后缀拼接起来, \\
使得到的新串回文,并且尽量长。$


$先贪心在首尾进行匹配,不匹配的时候再求一次中间段的最长 \\
回文前缀或后缀,这个东西可以用马拉车解决,只要以i为中心 \\
的回文半径r与i相等就更新。马拉车里有’#’需要扣下细节。 $

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(0);
#define pii pair<ll,ll>
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define rep(i,a,b) for(ll i=a;i<=(ll)b;++i)
#define per(i,a,b) for(ll i=a;i>=(ll)b;--i)
#define ll long long
#define lowbit(x) ((x)&(-x))
const int maxn=1e6+6;
char s[maxn],a[maxn],b[maxn];
struct Manacher{

int r[maxn<<1];

void build(string s){
int len = s.size();
string tem = "$#";
rep(i,0,len-1){
tem += s[i];
tem += '#';
}

int mx = 0,id = 0,l = tem.size();
r[l] = 0; tem[l] = 0;
for (int i=0;i<l;i++){
r[i] = mx>i ? min(r[2 * id-i],mx-i) : 1;
while(tem[i+r[i]] == tem[i-r[i]]) r[i]++;
if (i + r[i] > mx){
mx = i + r[i];
id = i;
}
}
}
} Ma;

int main()
{
IOS
int t; cin >> t;
while(t--){
string s; cin >> s;
int l = 0,r = s.size() - 1;
int pre = 0, suf = 0;
while(l < r){
if(s[l] == s[r]) {++l; --r;}
else break;
}
string tem = s.substr(l,r-l+1);
Ma.build(tem);
int n = tem.size();
rep(i,1,2 * n + 1){
if(i&1){
if(Ma.r[i]==i) pre=i-1;
}
else if(Ma.r[i]==i) pre=(i-1)/2*2+1;
}

reverse(tem.begin(),tem.end());
Ma.build(tem);
rep(i,1,2 * n + 1){
if(i&1){
if(Ma.r[i]==i) suf=i-1;
}
else if(Ma.r[i]==i) suf=(i-1)/2*2+1;
}

rep(i,0,l-1) cout << s[i];
if(pre > suf){
reverse(tem.begin(),tem.end());
rep(i,0,pre - 1) cout << tem[i];
}
else{
rep(i,0,suf - 1) cout << tem[i];
}
per(i,l-1,0) cout << s[i];
cout << "\n";
}
}
avatar Decaku 菜菜菜