【字符串入门专题1】【hdu4763】【未ac题】【扩展kmp exkmp】

本文介绍了一种算法,用于确定音乐节上表演曲目的最大可能主题段落长度。通过分析给定歌曲的结构,该算法能够找出符合特定格式要求的主题部分,即‘EAEBE’格式,其中E为主题段,而A和B可以是任意长度的其他部分。文章提供了实现这一功能的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Theme Section

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

引用书上的解释:假设歌曲长度为l,主旋律长度为n,将歌曲长度看做一个长为l的字符串s。主旋律长度l一定满足一下两个条件,1:next[l-n]==n,即该字符串以长度为n的前缀为后缀。2:max{next[n]...next[l-n-1]} > n ,即s[n...l-n-1]的某个长度为n的子串等于长度为n的前缀。首先求出next数组,然后就可以依此减少n的值,查看能否满足前两个条件,判断l是否为一个可行解。

AC代码:but  自己没有看懂   先留着  

#include<string.h>
#include<stdio.h>
#define N 11000000

int l,n;
int a[N];
char s[N];

int main()
{
	int t,i,j,p,maxl;
	scanf("%d",&t);
	while(t --)
	{
		getchar();
		scanf("%s",s);
		l = strlen(s);
		a[0] = l;
		i = 1;
		j = 0;
		p = -1;
		while(i < l)//求出next数组 
		{
			if(p == -1)
			{
				j = 0;
				do
					p++;
				while(s[i+p]==s[j+p]);
				a[i] = p;
			}
			else if(a[j] < p)
				a[i] = a[j];
			else if(a[j] > p)
			{
				j = 0;
				a[i] = p;
			}
			else 
			{
				j = 0;
				while(s[i+p] == s[j+p])
					p++;
				a[i] = p;
			}
			i++;
			j++;
			p--;
		}
		a[l] = 0;
		n = l/3;
		maxl = a[l-n-n];
		for(i = n; i < l-n-n; i ++)
			if(maxl < a[i])
				maxl = a[i];
		while(maxl<n||a[l-n]!=n)//将n从小到大进行比较 
		{
			n --;
			if(maxl < a[n]) maxl = a[n];
			if(maxl < a[l-n-n]) maxl = a[l-n-n];
			if(maxl < a[l-n-n-1]) maxl = a[l-n-n-1];
		}
		printf("%d\n",n);
	}
	return 0;
}


转载于:https://www.cnblogs.com/hellocheng/p/7350054.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值