Theme Section(主题部分)(kmp经典模板题) HDU - 4763

题目: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

中文大意

是时候听音乐了!许多流行音乐家被邀请加入我们的音乐节。他们每个人都会演奏一首他们的代表歌曲。为了让节目更有趣和更具挑战性,主持人会在歌曲的节奏上加入一些限制,即每首歌曲都需要有一个“主题部分”。主题部分在每首歌曲的开头、中间和结尾播放。更具体地说,给定主题部分 E,歌曲将采用“EAEBE”格式,其中部分 A 和部分 B 可以有任意数量的音符。请注意,有 26 种类型的音符,由小写字母“a”-“z”表示。

为了为音乐节做好准备,主持人想知道每首歌主题部分的最大可能长度。
输入
第一行的整数N表示音乐节的歌曲总数。以下 N 行中的每一行都由一个字符串组成,表示第 i (1 <= i <= N) 首歌曲的音符。字符串的长度不会超过 10^6。
输出
输出中有 N 行,其中第 i 行表示第 i 首歌曲主题部分的最大可能长度。
样本输入
5
xy
abc
aaa
aaaaba
aaxoaaaaa
样本输出
0
0
1
1
2

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char str[1000100];
int nex[1000100];
int slen;

void getnext()
{
	nex[0]=-1;
	int j=0, k=-1;
	while(j<slen)
	{
		if(k==-1||str[j]==str[k])
		{
			k++;
			j++;
			nex[j]=k;
		}
		else k=nex[k];
	}
	
}
int main()
{
	int n;
	cin>>n;
	while(n--)
	{
		int fact=0;
		scanf("%s",str);
		slen=strlen(str);
		getnext();
		for(int i=nex[slen]+1; i<=slen-nex[slen]; i++)
			if(nex[i]>=nex[slen]) fact=1;
		if(nex[slen]==slen-1) 
			cout<<"1"<<endl;
		else if(fact==1)
			cout<<nex[slen]<<endl;
		else cout<<"0"<<endl;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值