hdu

来源:互联网 发布:游戏王决斗盘 淘宝 编辑:程序博客网 时间:2024/05/20 09:26

Theme Section

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数组,刚开始看错题了,这道题看大佬都说水,都是第一道KMP,为啥我感觉好难啊,自己还是不太懂next数组;

题目大意:给你一串字符找符合”“EAEBE”的最多E是多少!!注意:字符串必须全部用上,也就是说字符串的末尾必须在前面能匹配!!!





先上代码

 #include<cstdio>#include<iostream>#include<cmath>#include<queue>#include<vector>#include<cstring>#include<algorithm>#include<map>#include<set>#include<stack>#include<sstream>#include<string>using namespace std;#define inf 0x3f3f3f3fint nextt[1000009];string a;void solve(){    int i=0;    int j=-1;    nextt[0]=-1;    int len=a.length();    while(i<len)    {        if(j==-1||a[i]==a[j])        {            i++;j++;            nextt[i]=j;        }        else j=nextt[j];    }}int main(){    int t;    cin>>t;    while(t--)    {        cin>>a;        solve();        int n=a.length();        int m=n;        int flag=0;        int re=nextt[a.length()];        while(flag&&re)         {            re=nextt[n];            for(int i=2*re;i<m-re;i++)            if(a[i]==nextt[i])            {                flag=0;                break;            }            n=nextt[n];        }        cout<<re<<endl;    }    return 0;}


对于这个代码相信NEXT数组都能看懂,就是下面暴力的地方不太好理解re代表E字符串的长度,for(int i=2*re;i < m-re;i++)就是个纯暴力的过程,就是搜中间的,为了防止重复(next数组储存原理)就从二倍长度搜起,结束位置毫无疑问就是字符总长度减E的长度了,我刚开始特别不理解n=nextt[n];这个是什么含义,后来大佬说NEXT数组储存方式,next存的是那个字符在第一个开始字符串的位置(我也不知道咋说,应该是我还是不太理解吧)第一次坑定是在字符串的最远的位置,然后逐步往前面移动,直到能够找到或无法再小为止,这也就是re的长度>0(while循环的退出条件,flag就不多说了,就一个标记);





大佬说的水题,53333.。。。。

原创粉丝点击