POJ-3974-Palindrome(马拉车)

时间:2019-09-28
本文章向大家介绍POJ-3974-Palindrome(马拉车),主要包括POJ-3974-Palindrome(马拉车)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

链接:

http://poj.org/problem?id=3974

题意:

Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, "Can you propose an efficient algorithm to find the length of the largest palindrome in a string?"

A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not.

The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!".

If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.

思路:

马拉车模板题.

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXN = 1e6+10;

int hw[MAXN*2], val[30], Sum[MAXN*2];
char s[MAXN], ss[MAXN*2];

void Manacher(char *str)
{
    int maxr = 0, mid;
    int len = strlen(str);
    for (int i = 1;i < len;i++)
    {
        if (i < maxr)
            hw[i] = min(hw[mid*2-i], maxr-i);
        else
            hw[i] = 1;
        while (str[i+hw[i]] == str[i-hw[i]])
            hw[i]++;
        if (hw[i]+i > maxr)
        {
            maxr = hw[i]+i;
            mid = i;
        }
    }
}

void Change(char *str, char *to)
{
    to[0] = to[1] = '#';
    int len = strlen(str);
    for (int i = 0;i < len;i++)
    {
        to[i*2+2] = str[i];
        to[i*2+3] = '#';
    }
    to[len*2+2] = 0;
}

int main()
{
    int cnt = 0;
    while (~scanf("%s", s))
    {
        if (s[0] == 'E')
            break;
        Change(s, ss);
        Manacher(ss);
        int ans = 0;
        int len = strlen(ss);
        for (int i = 0;i < len;i++)
            ans = max(ans, hw[i]);
        printf("Case %d: %d\n", ++cnt, ans-1);
    }

    return 0;
}

原文地址:https://www.cnblogs.com/YDDDD/p/11605378.html