hdu 4763 kmp算法

 个人觉得kmp是很神奇的一种算法,最近刚刚开始入门

hdu 4763

Theme Section

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3162    Accepted Submission(s): 1486


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
 
题目意思是一个字符串中前缀后缀相等且能在中间找到,重要的一个点是三者不能重叠
 1 #include<iostream>
 2 #include<string>
 3 
 4 using namespace std;
 5 
 6 int net[1000005];
 7 string a;
 8 
 9 void get()
10 {
11     net[0]=-1;
12     int i = 0, j = -1;
13     while(i<a.length())
14     {
15         if(j==-1||a[i]==a[j])
16         {
17             i++,j++;
18             net[i]=j;
19         }
20         else
21             j = net[j];
22     }
23 }
24 int main()
25 {
26     int t;
27     cin>>t;
28     while(t--)
29     {
30         cin>>a;
31         int sum = 0;
32         for(int i = 1; i < a.length(); i++)
33             if(a[0]!=a[i])
34               sum=1;
35         if(!sum)
36             sum=a.length()/3;
37         else
38         {
39             sum=0;
40             get();
41             int ans = net[a.length()];
42             for(int i = ans; i >0 && !sum; i=net[i])
43             {
44                 for(int j = i*2; j <= a.length()-i; j++)
45                 {
46                     if(net[j]>=i)
47                         sum=i;
48                 }
49             }
50         }
51         cout<<sum<<endl;
52     }
53     return 0;
54 }
原文地址:https://www.cnblogs.com/Xycdada/p/5967399.html