1. 程式人生 > >【KMP nx陣列】求字串首尾和中間都出現的最長子串 HDU

【KMP nx陣列】求字串首尾和中間都出現的最長子串 HDU

Theme Section

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


 

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

Source

#include <bits/stdc++.h>
using namespace std;

const int mn = 1000010;

char ch[mn], t1[mn], t2[mn];
int len;

int nx[mn];
void cal_next(char ch[])
{
	int len = strlen(ch);
	nx[0] = -1;
	int k = -1;
	for (int i = 1; i < len; i++)
	{
		while (k != -1 && ch[k + 1] != ch[i])
			k = nx[k];
		if (ch[k + 1] == ch[i])
			k++;
		nx[i] = k;
	}
}

int KMP(char a[], char b[])
{
	cal_next(b);

	int n = strlen(a), m = strlen(b);
	int k = -1;
	for (int i = 0; i < n; i++)
	{
		while (k > -1 && b[k + 1] != a[i])
			k = nx[k];
		if (b[k + 1] == a[i])
			k++;
		if (k == m - 1)
			return i - m + 1;
	}
	return -1;
}

int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		scanf("%s", ch);

		len = strlen(ch);
		cal_next(ch);

		int ans = 0;
		for (int i = nx[len - 1]; i != -1; i = nx[i])
		{
			if (3 * (i + 1) > len)  // 保證不重疊
				continue; 

			/// 每次按 nx[i] 減小長度查詢
			// 在 中間一段字串 查詢是否存在 前nx位字元
			for (int j = i + 1; j < len - i - 1; j++)
				t1[j - (i + 1)] = ch[j];
			t1[len - 2 * (i + 1)] = '\0';
			for (int j = 0; j <= i; j++)
				t2[j] = ch[j];
			t2[i + 1] = '\0';

			if (KMP(t1, t2) != -1)
			{
				ans = i + 1;
				break;
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}