UVA - 1328 Period KMP算法

KMP算法求循环节

F 数组存的是前一个循环节的位置,只要判断前一个是不是一个循环节就好了


#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 1000000 + 7, INF = 0x3f3f3f3f, mod = 1e9+7;
int n;
char s[maxn];
int f[maxn];

void init() {
    f[0] = f[1] = 0;
    for(int i = 1; i < n; ++i) {
        int j = f[i];
        while(j && s[j] != s[i]) j = f[j];
        f[i+1] = s[j] == s[i] ? j+1 : 0;
    }
}

void solve() {
    for(int i = 1; i < n; ++i) {
        int t = i - f[i];
        if( (i+1) % t == 0 && s[i] == s[f[i]]) {
            cout << i+1 << " " << (i+1) / t << endl;
        }
    }
    cout << endl;
}

int main() {

    int kase = 1;
    while(scanf("%d", &n) != EOF && n) {
        scanf("%s", s);
        init();
        printf("Test case #%d\n", kase++);
        solve();
    }

    return 0;
}


/*
3
aaa
12
aabaabaabaab
8
abababab
5
aaaaa
*/


你可能感兴趣的:(KMP算法,UVA,紫书蓝书)