HDU

来源:互联网 发布:中国古代数学 知乎 编辑:程序博客网 时间:2024/05/17 07:52
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
5xyabcaaaaaaabaaaxoaaaaa
Sample Output
00112


题意:

问是否存在这样形式的字符串:ABACA

其中B,C可以是空串,A是长度至少为一的串。

若存在则输出A的最长长度,否则输出0


主要利用 KMP 中的 next 数组来解决。

nex[len]表示第len位之前的字符串中 前nex[len]位 和 后nex[len] 相等
即 adbdad nex[6]=2;

(具体解析见代码)


代码:

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;char b[1000005];int nex[1000005];void get_next(char *b){int m=strlen(b);int j=-1,i=0;nex[0]=-1;while(i<m){if(j==-1 || b[i]==b[j])nex[++i]=++j;else j=nex[j];}}int main(){int t;scanf("%d",&t);while(t--){scanf("%s",b);get_next(b);int m=strlen(b);int f=1,ans=0;int n=m;//保证 i 的最大值不变 while(m>0 && f){int len=nex[m];//求出最大的前后缀个数 for(int i=len*2; i<=n-len && f; i++){//求中间是否存在于前后缀相同的个数 if(nex[i]==len){//存在时 ans=len;f=0;break;}}m=nex[m];//返回此时对应的上一个//例如 aabaaa 当前缀是aa时不满足情况;//此时m=nex[m]表示返回到第一个a ,进行接下来的前缀是a 的判断 }printf("%d\n",ans);}return 0;}



原创粉丝点击