码迷,mamicode.com
首页 > 其他好文 > 详细

POJ-3974-Palindrome(马拉车)

时间:2019-09-28 23:36:29      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:str   moment   char   lse   top   %s   模板   href   ble   

链接:

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;
}

POJ-3974-Palindrome(马拉车)

标签:str   moment   char   lse   top   %s   模板   href   ble   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!