1511: [POI2006]OKR-Periods of Words
Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 330 Solved: 200[][][]Description
一 个串是有限个小写字符的序列,特别的,一个空序列也可以是一个串. 一个串P是串A的前缀, 当且仅当存在串B, 使得 A = PB. 如果 P A 并且 P 不是一个空串,那么我们说 P 是A的一个proper前缀. 定义Q 是A的周期, 当且仅当Q是A的一个proper 前缀并且A是QQ的前缀(不一定要是proper前缀). 比如串 abab 和 ababab 都是串abababa的周期. 串A的最大周期就是它最长的一个周期或者是一个空串(当A没有周期的时候), 比如说, ababab的最大周期是abab. 串abc的最大周期是空串. 给出一个串,求出它所有前缀的最大周期长度之和.
Input
第一行一个整数 k ( 1 k 1 000 000) 表示串的长度. 接下来一行表示给出的串.
Output
输出一个整数表示它所有前缀的最大周期长度之和.
Sample Input
8 babababa
Sample Output
24
HINT
Source
【题解】
之前有n - nxt[n]是最小循环节
只需要不断往前跳nxt,跳到不能再跳
还是n - nxt
递推即可
我记得形成的东西好像叫KMP树来着?还是nxt树?还是fail树?
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #define min(a, b) ((a) < (b) ? (a) : (b))10 #define max(a, b) ((a) > (b) ? (a) : (b))11 #define abs(a) ((a) < 0 ? (-1 * (a)) : (a))12 inline void swap(long long &a, long long &b)13 {14 long long tmp = a;a = b;b = tmp;15 }16 inline void read(long long &x)17 {18 x = 0;char ch = getchar(), c = ch;19 while(ch < '0' || ch > '9') c = ch, ch = getchar();20 while(ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar();21 if(c == '-') x = -x;22 }23 24 const long long INF = 0x3f3f3f3f;25 const long long MAXN = 2000000 + 10;26 27 char s[MAXN];28 long long nxt[MAXN], cnt[MAXN], len; 29 30 int main()31 {32 read(len);scanf("%s", s);33 nxt[0] = -1;34 for(register long long i = 1, j = -1;i < len;++ i)35 {36 while(j >= 0 && s[i] != s[j + 1]) j = nxt[j];37 if(s[i] == s[j + 1]) ++ j;38 nxt[i] = j;39 }40 long long sum = 0;41 for(register long long i = 0;i < len;++ i)42 {43 long long now = nxt[i];44 if(now != -1 && cnt[now] != -1) now = cnt[now];45 if(now != -1) sum += i - now;46 cnt[i] = now;47 }48 printf("%lld", sum);49 return 0;50 }