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

描述:
给定一个字符串,找出至少添加多少个字符,才能使这个字符串成为回文串
思路:
字符串哈希,首先将字符串反转,然后进行前缀哈希,每次查询字符串a的后i位和字符串b的前i位,如果相等就更新指针,最后判断一下,如果说本身就是回文串就输出0。
代码:

#include <iostream>

using namespace std;

const int N = 400010, P = 131;

typedef unsigned long long ULL;

ULL h[N], p[N], h2[N];
char a[N], b[N];

ULL get(int l, int r, int s)
{
    if (s == 1) return h[r] - h[l - 1] * p[r - l + 1];
    else return h2[r] - h2[l - 1] * p[r - l + 1];
}

int main()
{
    int n;
    cin >> n;
    cin >> a + 1;
    int cnt = 1;
    for (int i = n; i >= 1; i -- )
        b[cnt ++ ] = a[i];
    
    p[0] = 1;
    for (int i = 1; i <= n; i ++ )
    {
        p[i] = p[i - 1] * P;
        h[i] = h[i - 1] * P + a[i];
        h2[i] = h2[i - 1] * P + b[i];
    }
    
    int k = 0;
    for (int i = 1; i < n; i ++ )
        if (get(1, i, 2) == get(n - i + 1, n, 1)) k = i;  // 判断前n - 1位是否相等
        
    if (get(1, n, 2) == get(1, n, 1)) cout << 0 << endl;  // 判断本身是否是回文串
    else cout << n - k << endl;
    
    return 0;
}
posted on 2021-04-07 20:55  Laurance  阅读(68)  评论(0编辑  收藏  举报