POJ-2752-Seek the Name, Seek the Fame

Seek the Name, Seek the Fame

The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm:

Step1. Connect the father’s name and the mother’s name, to a new string S.
Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S).
Example:
Father=‘ala’, Mother=‘la’, we have S = ‘ala’+‘la’ = ‘alala’. Potential prefix-suffix strings of S are {‘a’, ‘ala’, ‘alala’}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:)
Input
The input contains a number of test cases. Each test case occupies a single line that contains the string S described above.
Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.
Output
For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby’s name.
Sample Input
ababcababababcabab
aaaaa
Sample Output
2 4 9 18
1 2 3 4 5
题目传送门:POJ-2752

解题思路

这个题的大概意思就是要求一个字符串的最长公共前缀和后缀,求是的确很好求但是如何输出呢?每个位置的最长公共前后缀这就是个问题,其实也不是很难,我们只需把next数组的值到这输出一下就行,就想并查集一样,一直循环就行了,因为我们在求next数组的时候已经把位置给记录好了

代码

#include<string.h>
#include<vector>
#include<stdio.h>

using namespace std;
#define vce vector<int>
char a[400400];
int v[400400];
int nu[400400];
int main()
{
	while(~scanf("%s",a))
	{
		int len=strlen(a);
		memset(v,0,sizeof v);
		v[0]=0;
		int j;
		//求next数组 
		for(int i=1;i<len;i++)
		{
			j=v[i-1];
			while(j>0&&a[i]!=a[j])
			{
				j=v[j-1];
			}
			if(a[i]==a[j]) j++;
			v[i]=j;
		}
		int i=v[len-1];
		nu[0]=len;//需要将数组倒着存一下 
		int k=1;
		while(i!=0)//一旦i=0就说明找到头了,不用找了 
		{
			if(i>0) nu[k++]=i;
		    i=v[i-1];
		}
		for(int i=k-1;i>=0;i--) 
		{
			if(i==k-1) printf("%d",nu[i]);
			else printf(" %d",nu[i]);
		}
		printf("\n");
	}
	return 0;
}
发布了49 篇原创文章 · 获赞 14 · 访问量 4364

猜你喜欢

转载自blog.csdn.net/qq_43750980/article/details/99684766
今日推荐