题目链接:https://ac.nowcoder.com/acm/contest/7817/A
题目描述
Fernando was hired by the University of Waterloo to finish a development project the university started some time ago. Outside the campus, the university wanted to build its representative bungalow street for important foreign visitors and collaborators.
Currently, the street is built only partially, it begins at the lake shore and continues into the forests, where it currently ends. Fernando’s task is to complete the street at its forest end by building more bungalows there. All existing bungalows stand on one side of the street and the new ones should be built on the same side. The bungalows are of various types and painted in various colors.
The whole disposition of the street looks a bit chaotic to Fernando. He is afraid that it will look even more chaotic when he adds new bungalows of his own design. To counterbalance the chaos of all bungalow shapes, he wants to add some order to the arrangement by choosing suitable colors for the new bungalows. When the project is finished, the whole sequence of bungalow colors will be symmetric, that is, the sequence of colors is the same when observed from either end of the street.
Among other questions, Fernando wonders what is the minimum number of new bungalows he needs to build and paint appropriately to complete the project while respecting his self-imposed bungalow color constraint.
输入描述:
The first line contains one integer N (1 ≤ N ≤ 4·105 ), the number of existing bungalows in the street. The next line describes the sequence of colors of the existing bungalows, from the beginning of the street at the lake. The line contains one string composed of N lowercase letters (“a” through “z”), where different letters represent different colors.
输出描述:
Output the minimum number of bungalows which must be added to the forest end of the street and painted appropriately to satisfy Fernando’s color symmetry demand.
输入
3
abb
输出
1
分析
我们只要找出最靠右的最大的回文子串,那么要放的最少数量即 n - 这个回文子串的长度。
可以用 Manacher 算法来快速找出每个点的回文子串的半径,从左往右遍历每个点,如果半径刚好到达,这个点就是我们要找的最靠右的最大的回文子串。
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 4e5 + 5;
const ll mod = 1e9 + 7;
int Case,n;
char s[N * 2], str[N * 2];
int Len[N * 2];
void getstr() {//重定义字符串
int k = 0;
str[k++] = '@';//开头加个特殊字符防止越界
for (int i = 0; i < n; i++) {
str[k++] = '#';
str[k++] = s[i];
}
str[k++] = '#';
n = k;
str[k] = 0;//字符串尾设置为0,防止越界
}
void manacher() {
int mx = 0, id;//mx为最右边,id为中心点
for (int i = 1; i < n; i++) {
if (mx > i) Len[i] = min(mx - i, Len[2 * id - i]);//判断当前点超没超过mx
else Len[i] = 1;//超过了就让他等于1,之后再进行查找
while (str[i + Len[i]] == str[i - Len[i]]) Len[i]++;//判断当前点是不是最长回文子串,不断的向右扩展
if (Len[i] + i > mx) {//更新mx
mx = Len[i] + i;
id = i;//更新中间点
}
}
}
void solve(){
scanf("%d",&n);
int t = n;
scanf("%s",s);
getstr();
manacher();
for(int i=1;i<n;i++){
if(Len[i]+i==n){
printf("%d",max(0,t-Len[i] + 1));
return;
}
}
}
int main(){
Case = 1;
//scanf("%d",&Case);
while(Case--){
solve();
}
}