牛客网暑期ACM多校训练营(第三场): E. Sort String(KMP)

链接:https://www.nowcoder.com/acm/contest/141/E
来源:牛客网
 

题目描述

Eddy likes to play with string which is a sequence of characters. One day, Eddy has played with a string S for a long time and wonders how could make it more enjoyable. Eddy comes up with following procedure:

1. For each i in [0,|S|-1], let Si be the substring of S starting from i-th character to the end followed by the substring of first i characters of S. Index of string starts from 0.
2. Group up all the Si. Si and Sj will be the same group if and only if Si=Sj.
3. For each group, let Lj be the list of index i in non-decreasing order of Si in this group.
4. Sort all the Lj by lexicographical order.

Eddy can't find any efficient way to compute the final result. As one of his best friend, you come to help him compute the answer!

输入描述:

Input contains only one line consisting of a string S.

1≤ |S|≤ 106
S only contains lowercase English letters(i.e. ).

输出描述:

First, output one line containing an integer K indicating the number of lists.
For each following K lines, output each list in lexicographical order.
For each list, output its length followed by the indexes in it separated by a single space.

输入

abab

输出

2
2 0 2
2 1 3

题意:给你一个长度为n的字符串str,定义字符串S[i] = str[i+1~n]+str[1~i],如果S[i]=S[j],那么两个字符串在同一组里面(也就是对于任意一组里面所有字符串全部相同)求出总共有多少不同的组,分别都有哪些字符串

结论:如果字符串str是某个长度为len的字符串重复k次得出来的(例如"acckacckacck"是"acck"重复3次)那么S[i]和S[i+len]就一定在同一组里面

#include<stdio.h>
#include<string.h>
#include<vector>
char str[1000005];
int next[1000005], ans[1000005];
int main(void)
{
	int n, i, j, dis, cnt;
	scanf("%s", str+1);
	n = strlen(str+1);
	i = 1, j = 0;
	next[1] = 0;
	while(i<=n)
	{
		if(j==0 || str[i]==str[j])
		{
			next[i] = j;
			i++, j++;
		}
		else
			j = next[j];
	}
	dis = next[n];
	for(i=n;i>=n-next[n];i--)
	{
		if(next[i]-1!=next[i-1])
			break;
	}
	dis = i;
	for(i=1;i+dis<=n;i++)
	{
		if(str[i]!=str[i+dis])
			break;
	}
	if(i+dis==n+1)
	{
		printf("%d\n", dis);
		for(i=1;i<=dis;i++)
		{
			cnt = 0;
			for(j=0;i+j<=n;j+=dis)
				ans[++cnt] = i+j;
			printf("%d", cnt);
			for(j=1;j<=cnt;j++)
				printf(" %d", ans[j]-1);
			puts("");
		}
	}
	else
	{
		for(i=1;i<=n;i++)
			printf("1 %d\n", i-1);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Jaihk662/article/details/81223986
今日推荐