BZOJ1355: [Baltic2009]Radio Transmission
1355: [Baltic2009]Radio Transmission
Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 1100 Solved: 745
[Submit][Status][Discuss]
Description
给你一个字符串,它是由某个字符串不断自我连接形成的。
但是这个字符串是不确定的,现在只想知道它的最短长度是多少.
Input
第一行给出字符串的长度,1 < L ≤ 1,000,000.
第二行给出一个字符串,全由小写字母组成.
Output
输出最短的长度
Sample Input
8
cabcabca
cabcabca
Sample Output
3
HINT
对于样例,我们可以利用"abc"不断自我连接得到"abcabcabc",读入的cabcabca,是它的子串
Source
回顾一下KMP。。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 #include <queue> 7 #include <vector> 8 #include <cmath> 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(int &a, int &b) 13 { 14 long long tmp = a;a = b;b = tmp; 15 } 16 inline void read(int &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 int INF = 0x3f3f3f3f; 25 const int MAXN = 1000000 + 10; 26 27 int nxt[MAXN],len; 28 char s[MAXN]; 29 30 int main() 31 { 32 read(len); 33 scanf("%s", s); 34 nxt[0] = -1; 35 for(register int i = 1, j = -1;i < len;++ i) 36 { 37 while(j >= 0 && s[i] != s[j + 1]) j = nxt[j]; 38 if(s[i] == s[j + 1]) ++ j; 39 nxt[i] = j; 40 } 41 printf("%d", len - (nxt[len - 1] + 1)); 42 return 0; 43 }