【字符串入门专题1】【hdu4763】【未ac题】【扩展kmp exkmp】

时间:2021-03-15 22:15:51

Theme Section

Problem Description It's time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a 'theme section'. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of 'EAEBE', where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters 'a' - 'z'.

To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?
 
Input The integer N in the first line denotes the total number of songs in the festival. Each of the following N lines consists of one string, indicating the notes of the i-th (1 <= i <= N) song. The length of the string will not exceed 10^6.  
Output There will be N lines in the output, where the i-th line denotes the maximum possible length of the theme section of the i-th song.
 
Sample Input
5
xy
abc
aaa
aaaaba
aaxoaaaaa
 
Sample Output
0
0
1
1
2

引用书上的解释:假设歌曲长度为l,主旋律长度为n,将歌曲长度看做一个长为l的字符串s。主旋律长度l一定满足一下两个条件,1:next[l-n]==n,即该字符串以长度为n的前缀为后缀。2:max{next[n]...next[l-n-1]} > n ,即s[n...l-n-1]的某个长度为n的子串等于长度为n的前缀。首先求出next数组,然后就可以依此减少n的值,查看能否满足前两个条件,判断l是否为一个可行解。

AC代码:but  自己没有看懂   先留着  

#include<string.h>
#include<stdio.h>
#define N 11000000

int l,n;
int a[N];
char s[N];

int main()
{
int t,i,j,p,maxl;
scanf("%d",&t);
while(t --)
{
getchar();
scanf("%s",s);
l = strlen(s);
a[0] = l;
i = 1;
j = 0;
p = -1;
while(i < l)//求出next数组
{
if(p == -1)
{
j = 0;
do
p++;
while(s[i+p]==s[j+p]);
a[i] = p;
}
else if(a[j] < p)
a[i] = a[j];
else if(a[j] > p)
{
j = 0;
a[i] = p;
}
else
{
j = 0;
while(s[i+p] == s[j+p])
p++;
a[i] = p;
}
i++;
j++;
p--;
}
a[l] = 0;
n = l/3;
maxl = a[l-n-n];
for(i = n; i < l-n-n; i ++)
if(maxl < a[i])
maxl = a[i];
while(maxl<n||a[l-n]!=n)//将n从小到大进行比较
{
n --;
if(maxl < a[n]) maxl = a[n];
if(maxl < a[l-n-n]) maxl = a[l-n-n];
if(maxl < a[l-n-n-1]) maxl = a[l-n-n-1];
}
printf("%d\n",n);
}
return 0;
}