首页 > 代码库 > hdu4763 kmp
hdu4763 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?
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
题意:找三个子串,第一个必须在开头
题解:kmp,刚开始想错了,以为是枚举,tle了,题目又看了一遍才明白意思,用next处理能快很多
不用遍历了
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<vector> #include<cstdio> #include<iomanip> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define pi acos(-1) #define ll long long #define mod 1000000007 using namespace std; const int N=1000000+5,maxn=1000000+5,inf=1e9+5; int Next[N]; void getnext(string str) { int k=-1; Next[0]=-1; for(int i=1;i<str.size();i++) { while(k>-1&&str[k+1]!=str[i])k=Next[k]; if(str[k+1]==str[i])k++; Next[i]=k; } } bool kmp(string ptr,string str) { int k=-1,ans=0; for(int i=0;i<ptr.size();i++) { while(k>-1&&str[k+1]!=ptr[i])k=Next[k]; if(str[k+1]==ptr[i])k++; if(k==str.size()-1)return 1; } return 0; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--){ string ptr; cin>>ptr; getnext(ptr); int k=Next[ptr.size()-1],ans=0; while(k!=-1){ string str=ptr.substr(0,k+1),p=ptr.substr(k+1,ptr.size()-2*k-2); // cout<<p<<" "<<str<<endl; if((k+1)*3<=ptr.size()&&kmp(p,str)) { ans=k+1; break; } k=Next[k]; } cout<<ans<<endl; } return 0; }
hdu4763 kmp
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。