Z.Theme Section

来源:互联网 发布:甲骨文java培训骗局 编辑:程序博客网 时间:2024/06/05 05:14

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

题解:

没想到这题这么水。
先用next数组求出最长的前后缀长度。
之后暴力枚举即可。每次把前后缀长度减一,看字符串内部有无此字符。
47ms

代码:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <windows.h>using namespace std;const int maxn = 1e6+100;int nt[maxn];int len;char s[maxn];void getNext(){    int j,k;    j=0;k=-1;nt[0]=-1;    while(j<len)    {        if(k==-1||s[j]==s[k])            nt[++j]=++k;        else            k=nt[k];    }}char tmp[maxn];int main(){    int N;    scanf("%d",&N);    while(N--)    {        scanf("%s",s);        len = strlen(s);        getNext();        if(nt[len]==0)        {            cout<<0<<endl;            continue;        }         int l=nt[len],pos;         while(1)         {              int i;              for(i=0;i<l;i++)              {                  tmp[i]=s[i];              }              tmp[i]='\0';              pos =strstr(s+l,tmp)-s;              if(pos<len-l&&pos>=l) break;              l--;         }         cout<<l<<endl;    }    return 0;}
原创粉丝点击