HDU4763 Theme Section(kmp

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?

InputThe 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.OutputThere 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

多组数据,题意大概是:给一个字符串,如果是形为EAEBE字符串(e,a,b各代表原字符串的连续字串,并且无重合部分)则输出e的最大长度(a,b字符串长度可以为0)

思路是先用next数组处理e的最大长度,再回到字符中间判断是否有e字符串满足要求

虽然ac了但是总感觉有欠缺的地方emmmm或许是数据太弱了

因为觉得http://codeforces.com/problemset/problem/126/B 这两道题思路很像,而这道题用原来的思路写出锅了...还有一点没想通,,等想明白再说

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 using namespace std;
 5 const int maxn=1e6+5;
 6 const int mod = 1e4+7;
 7 int net[maxn],len;
 8 char c[maxn];
 9 void getnext(){
10     int l = strlen(c);
11     int i = 0,j = -1;
12     net[0]=-1;
13     while(i<l){
14         if(j==-1||c[i]==c[j]) net[++i]=++j;
15         else j = net[j];
16     }
17 }
18 int main()
19 {
20     int t;
21     cin>>t;
22     while(t--){
23         cin>>c;
24         getnext();
25         int l = strlen(c);
26         if(net[l]==l-1){
27             cout<<l/3<<endl;continue;
28         }
29         int res=min(net[l],l/3);
30         if(!res){
31             cout<<"0"<<endl;continue;
32         }
33         int ans=0;
34         for(int i = res;i <l-res;++i){
35             ans=max(ans,net[i]);
36         }
37         cout<<min(ans,res)<<endl;
38     }
39     return 0;
40 }

猜你喜欢

转载自www.cnblogs.com/h404nofound/p/11703889.html