poj1961
思路:
满足 $i % (i-prefix[i]) == 0$ 且i != i-prefix[i]
,说明当前子串S[1~i]
的长度是(最长公共前后缀)的前缀长度的倍数,那么 i/(i-prefix[i])
就是循环节的个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <iostream> #include <string.h> using namespace std; const int maxn=1e6+10; char pattern[maxn]; int prefix[maxn];
void prefix_table(char pattern[],int prefix[],int n) { prefix[0] = 0; int i = 1, len = 0; while ( i < n ) { if ( pattern[i] == pattern[len]) { len++; prefix[i] = len; i++; } else { if ( len > 0 ) { len = prefix[ len - 1 ]; } else { prefix[i] = len; i++; } } } } void move_prefix(int prefix[],int n) { for (int i = n; i>0; i--) { prefix[i] = prefix[i-1]; } prefix[0] = -1; }
int main() {
int k; int cnt = 0; while ( scanf("%d",&k) && k ) { scanf("%s",pattern);
int n = strlen(pattern);
prefix_table(pattern,prefix,n);
move_prefix(prefix,n);
printf("Test case #%d\n",++cnt);
for (int i=1; i<=n;i++) { int dif = i - prefix[i]; if ( i!=dif && (i%dif == 0) ) { printf("%d %d\n", i, i/dif ); } } printf("\n"); } return 0; }
|