Last active
December 21, 2015 00:28
-
-
Save junjiah/6219985 to your computer and use it in GitHub Desktop.
POJ 1961 - Period, using 'next' array from KMP algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Solving POJ 1961 Period */ | |
#include <iostream> | |
#include <cstring> | |
using namespace std; | |
char input[1000005]; | |
int next[1000006]; | |
class KMP_algorithm { | |
public: | |
void find_period(const char* pattern, int sz) { | |
int j = 0, i = 1; | |
for (int i=1; i<sz+1; i++) next[i] = 0; | |
next[0] = -1; | |
while (i < sz) { | |
if (j == -1 || pattern[i] == pattern[j]) { | |
next[++i] = ++j; | |
} | |
else { | |
j = next[j]; | |
} | |
} | |
for (i=2; i<=sz; ++i) { | |
if (next[i] != 0 && i % (i-next[i]) == 0) | |
printf("%d %d\n", i, i/(i-next[i])); | |
} | |
cout << endl; | |
} | |
}; | |
int main() { | |
KMP_algorithm kmp; | |
int size, num = 0; | |
while (scanf("%d", &size)==1) { | |
if (size == 0) break; | |
scanf("%s", input); | |
printf("Test case #%d\n", ++num); | |
kmp.find_period(input, size); | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment