后缀数组 - 求最长回文子串 + 模板题 --- ural 1297

2024-09-05 17:32

本文主要是介绍后缀数组 - 求最长回文子串 + 模板题 --- ural 1297,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1297. Palindrome

Time Limit: 1.0 second
Memory Limit: 16 MB
The “U.S. Robots” HQ has just received a rather alarming anonymous letter. It states that the agent from the competing «Robots Unlimited» has infiltrated into “U.S. Robotics”. «U.S. Robots» security service would have already started an undercover operation to establish the agent’s identity, but, fortunately, the letter describes communication channel the agent uses. He will publish articles containing stolen data to the “Solaris” almanac. Obviously, he will obfuscate the data, so “Robots Unlimited” will have to use a special descrambler (“Robots Unlimited” part number NPRx8086, specifications are kept secret).
Having read the letter, the “U.S. Robots” president recalled having hired the “Robots Unlimited” ex-employee John Pupkin. President knows he can trust John, because John is still angry at being mistreated by “Robots Unlimited”. Unfortunately, he was fired just before his team has finished work on the NPRx8086 design.
So, the president has assigned the task of agent’s message interception to John. At first, John felt rather embarrassed, because revealing the hidden message isn’t any easier than finding a needle in a haystack. However, after he struggled the problem for a while, he remembered that the design of NPRx8086 was still incomplete. “Robots Unlimited” fired John when he was working on a specific module, the text direction detector. Nobody else could finish that module, so the descrambler will choose the text scanning direction at random. To ensure the correct descrambling of the message by NPRx8086, agent must encode the information in such a way that the resulting secret message reads the same both forwards and backwards.
In addition, it is reasonable to assume that the agent will be sending a very long message, so John has simply to find the longest message satisfying the mentioned property.
Your task is to help John Pupkin by writing a program to find the secret message in the text of a given article. As NPRx8086 ignores white spaces and punctuation marks, John will remove them from the text before feeding it into the program.

Input

The input consists of a single line, which contains a string of Latin alphabet letters (no other characters will appear in the string). String length will not exceed 1000 characters.

Output

The longest substring with mentioned property. If there are several such strings you should output the first of them.

Sample

input
ThesampletextthatcouldbereadedthesameinbothordersArozaupalanalapuazorA
output
ArozaupalanalapuazorA 

 

Mean: 

 给你一个字符串,让你输出字符串的最长回文子串。

analyse:

求最长回文串有很多方法,最经典的莫过于Manacher算法,时间复杂度O(n)。

这里就主要介绍一下用后缀数组的方法。

用后缀数组怎么求回文串呢?

原理和上一篇求最长公共子序列一样,我们把s1反转后接到s1后面得到S串,那么s1的最长回文串必定存在于S中,我们只需要求一下S的height数组,然后寻找来自于不同的两个串的height[i]的最大值,然后记录一下开始位置和长度,最后输出即可。

Time complexity:O(nlogn)

 

Source code:

 Suffix Arrays:

/*
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-05-09-21.22
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#define  LL long long
#define  ULL unsigned long long
using namespace std;
const int MAXN = 2015;
//以下为倍增算法求后缀数组
int wa [ MAXN ], wb [ MAXN ], wv [ MAXN ], Ws [ MAXN ];
int cmp( int * r , int a , int b , int l)
{ return r [ a ] == r [b ] && r [ a + l ] == r [b + l ];}
/**< 传入参数:str,sa,len+1,ASCII_MAX+1 */
void da( const char * r , int * sa , int n , int m)
{
      int i , j ,p , * x = wa , * y = wb , * t;
      for( i = 0; i < m; i ++) Ws [ i ] = 0;
      for( i = 0; i <n; i ++) Ws [ x [ i ] = r [ i ]] ++;
      for( i = 1; i < m; i ++) Ws [ i ] += Ws [ i - 1 ];
      for( i =n - 1; i >= 0; i --) sa [ -- Ws [ x [ i ]]] = i;
      for( j = 1 ,p = 1; p <n; j *= 2 , m =p)
      {
            for(p = 0 , i =n - j; i <n; i ++) y [p ++ ] = i;
            for( i = 0; i <n; i ++) if( sa [ i ] >= j) y [p ++ ] = sa [ i ] - j;
            for( i = 0; i <n; i ++) wv [ i ] = x [ y [ i ]];
            for( i = 0; i < m; i ++) Ws [ i ] = 0;
            for( i = 0; i <n; i ++) Ws [ wv [ i ]] ++;
            for( i = 1; i < m; i ++) Ws [ i ] += Ws [ i - 1 ];
            for( i =n - 1; i >= 0; i --) sa [ -- Ws [ wv [ i ]]] = y [ i ];
            for( t = x , x = y , y = t ,p = 1 , x [ sa [ 0 ]] = 0 , i = 1; i <n; i ++)
                  x [ sa [ i ]] = cmp( y , sa [ i - 1 ], sa [ i ], j) ?p - 1 :p ++;
      }
      return;
}
int sa [ MAXN ], Rank [ MAXN ], height [ MAXN ];
/**< str,sa,len */
void calheight( const char * r , int * sa , int n)
{
      int i , j , k = 0;
      for( i = 1; i <=n; i ++) Rank [ sa [ i ]] = i;
      for( i = 0; i <n; height [ Rank [ i ++ ]] = k)
            for( k ? k --: 0 , j = sa [ Rank [ i ] - 1 ]; r [ i + k ] == r [ j + k ]; k ++);
      // Unified
      for( int i =n; i >= 1; -- i) ++ sa [ i ], Rank [ i ] = Rank [ i - 1 ];
}

char s1 [ MAXN ], s2 [ MAXN ];
int main()
{
      while( ~ scanf( "%s" , s1))
      {
            int l1 = strlen( s1);
            strcat( s1 , "{");
            strcpy( s2 , s1);
            for( int i = 0; i < l1; ++ i) s1 [ i + l1 + 1 ] = s2 [ l1 - i - 1 ];
            int len = strlen( s1);
            da( s1 , sa , len + 1 , 130);
            calheight( s1 , sa , len);
            int sta = 0 , maxLen = 1 , l , r;
            for( int i = 1; i <= len; ++ i)
            {
                  l = min( sa [ i ] - 1 , sa [ i - 1 ] - 1);
                  r = max( sa [ i ] - 1 , sa [ i - 1 ] - 1);
                  if(( l < l1 && r > l1) && ( len - r == l + height [ i ]))
                  {
                        if( height [ i ] > maxLen)
                              maxLen = height [ i ], sta = l;
                        else if( height [ i ] == maxLen)
                              sta = min( sta , l);
                  }
            }
            for( int i = sta , j = 0; j < maxLen; ++ i , ++ j)
                printf( "%c" , s1 [ i ]);
            puts( "");
      }
      return 0;
}

 

 Manacher:

/*
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-09-12-15.41
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#define max(a,b) (a>b?a:b)
using namespace std;
typedef long long( LL);
typedef unsigned long long( ULL);
const double eps( 1e-8);

/** O(n)内求出所有回文串
*原串 :abaaba
*Ma串 :.,a,b,a,a,b,a,
*Mp[i]:Ma串中,以字符Ma[i]为中心的最长回文子串的半径长度(包括Ma[i],也就是把回文串对折后的长度).
****经过对原串扩展处理后,将奇数串的情况也合并到了偶数的情况(不需要考虑奇数串)
*/
const int MAXN = 1050;
char Ma [ MAXN * 2 ],s [ MAXN ];
int Mp [ MAXN * 2 ], Mplen;
void Manacher( char s [], int len)
{
      int le = 0;
      Ma [ le ++ ] = '.';
      Ma [ le ++ ] = ',';
      for( int i = 0; i < len; ++ i)
      {
            Ma [ le ++ ] =s [ i ];
            Ma [ le ++ ] = ',';
      }
      Mplen = le;
      Ma [ le ] = 0;
      int pnow = 0 , pid = 0;
      for( int i = 1; i < le; ++ i)
      {
            if( pnow > i)
                  Mp [ i ] = min( Mp [ 2 * pid - i ], pnow - i);
            else
                  Mp [ i ] = 1;
            for(; Ma [ i - Mp [ i ]] == Ma [ i + Mp [ i ]]; ++ Mp [ i ]);
            if( i + Mp [ i ] > pnow)
            {
                  pnow = i + Mp [ i ];
                  pid = i;
            }
      }
}

int main()
{
      ios_base :: sync_with_stdio( false);
      cin . tie( 0);
      while( ~ scanf( "%s" ,s))
      {
            Manacher(s , strlen(s));
            int maxLen = 1 , idx = 0;
            for( int i = 0; i < Mplen; ++ i)
            {
                  if( Mp [ i ] > maxLen)
                        maxLen = Mp [ i ], idx = i;
            }
            for( int i =( idx - maxLen + 1) / 2 , j = 0; j < maxLen - 1; ++ i , ++ j)
                  printf( "%c" ,s [ i ]);
            puts( "");
//            cout<<maxLen-1<<endl;
      }
      return 0;
}

 

这篇关于后缀数组 - 求最长回文子串 + 模板题 --- ural 1297的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1139608

相关文章

C++原地删除有序数组重复项的N种方法

《C++原地删除有序数组重复项的N种方法》给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度,不要使用额外的数组空间,你必须在原地修改输入数组并在使用O(... 目录一、问题二、问题分析三、算法实现四、问题变体:最多保留两次五、分析和代码实现5.1、问题分析5.

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

Java中数组转换为列表的两种实现方式(超简单)

《Java中数组转换为列表的两种实现方式(超简单)》本文介绍了在Java中将数组转换为列表的两种常见方法使用Arrays.asList和Java8的StreamAPI,Arrays.asList方法简... 目录1. 使用Java Collections框架(Arrays.asList)1.1 示例代码1.

C++实现回文串判断的两种高效方法

《C++实现回文串判断的两种高效方法》文章介绍了两种判断回文串的方法:解法一通过创建新字符串来处理,解法二在原字符串上直接筛选判断,两种方法都使用了双指针法,文中通过代码示例讲解的非常详细,需要的朋友... 目录一、问题描述示例二、解法一:将字母数字连接到新的 string思路代码实现代码解释复杂度分析三、

C++一个数组赋值给另一个数组方式

《C++一个数组赋值给另一个数组方式》文章介绍了三种在C++中将一个数组赋值给另一个数组的方法:使用循环逐个元素赋值、使用标准库函数std::copy或std::memcpy以及使用标准库容器,每种方... 目录C++一个数组赋值给另一个数组循环遍历赋值使用标准库中的函数 std::copy 或 std::

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

关于最长递增子序列问题概述

《关于最长递增子序列问题概述》本文详细介绍了最长递增子序列问题的定义及两种优化解法:贪心+二分查找和动态规划+状态压缩,贪心+二分查找时间复杂度为O(nlogn),通过维护一个有序的“尾巴”数组来高效... 一、最长递增子序列问题概述1. 问题定义给定一个整数序列,例如 nums = [10, 9, 2

Java 字符数组转字符串的常用方法

《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu