牛客网暑期ACM多校训练营(第三场) E-Sort String next数组的应用
链接: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!
输入
abab
输出
2 2 0 2 2 1 3
题目大意: 给一个字符串,然后将字符串前i个字符移到组字符串的后面,组成新的字符串,如果有遇到相同的字符串分为一组,然后问有多少组,每组按字典序输出字符串的下标
例如 abab
i = 0 的时候,就是前0个字符串移到后面 也就是 abab
i =1 的时候 就是 baba
i=2 的时候 ,就是 abab
i=3的时候,就是 baba
所以有两组相同的,每组有两个数
通过next数组找到最小循环节, 如果 len % (len - next[len]) == 0 说明都是由最小循环节构成的。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int maxn=1e6+10; int nexts[maxn]; char str[maxn]; void get_next(int len){ int i=0,j=-1; nexts[0]=-1; while(i<len){ if(j==-1||str[i]==str[j]){ i++,j++; nexts[i]=j; } else j=nexts[j]; } } int main() { scanf("%s", &str); int len=strlen(str); get_next(len); int x=len-nexts[len]; if(len%x!=0){ scanf("%d\n",&len); for(int i=0;i<len;i++){ printf("1 %d\n",i); } } else{ printf("%d\n",x); for(int i=0;i<x;i++){ printf("%d",len/x); for(int j=i;j<len;j+=x) { printf(" %d",j); } printf("\n"); } } return 0; }