标签:扩展kmp
1 341
Case 1: 1 1 1
/************************************************************************* > File Name: hdu4333.cpp > Author: ALex > Mail: 405045132@qq.com > Created Time: 2015年01月23日 星期五 14时26分40秒 ************************************************************************/ #include <map> #include <set> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 2000010; char T[N], S[N]; int next[N]; int next2[N]; int extend[N]; void EXTEND_KMP () { int lens = strlen (S); int lent = strlen (T); next[0] = lent; int i, j, p, L; j = 0; while (j + 1 < lent && T[j] == T[j + 1]) { ++j; } next[1] = j; int a = 1; for (i = 2; i < lent; ++i) { p = next[a] + a - 1; L = next[i - a]; if (i + L < p + 1) { next[i] = L; } else { j = max (0, p - i + 1); while (i + j < lent && T[i + j] == T[j]) { ++j; } next[i] = j; a = i; } } j = 0; while (j < lens && S[j] == T[j]) { ++j; } extend[0] = j; a = 0; for (i = 1; i < lens; ++i) { p = extend[a] + a - 1; L = next[i - a]; if (L + i < p + 1) { extend[i] = L; } else { j = max(0, p - i + 1); while (i + j < lens && j < lent && S[i + j] == T[j]) { ++j; } extend[i] = j; a = i; } } } void get_next() { int len = strlen (T); next2[0] = -1; int j = 0; int k = -1; while (j < len) { if (k == -1 || T[k] == T[j]) { ++k; ++j; next2[j] = k; } else { k = next2[k]; } } } int main () { int t; scanf("%d", &t); int icase = 1; while (t--) { scanf("%s", T); strcpy (S, T); strcat (S, T); get_next (); EXTEND_KMP (); int lens = strlen (S); int lent = strlen (T); int ans1 = 0, ans2 = 0, ans3 = 0; for (int i = 0; i < lent; ++i) { if (extend[i] >= lent) { ++ans2; } else { if (S[i + extend[i]] < T[extend[i]]) { ++ans1; } else { ++ans3; } } } int ret = 1; // printf("%d %d %d\n", ans1, ans2, ans3); if (lent % (lent - next2[lent]) == 0) { ret = lent / (lent - next2[lent]); } printf ("Case %d: %d %d %d\n", icase++, ans1 / ret, ans2 / ret, ans3 / ret); } return 0; }
标签:扩展kmp
原文地址:http://blog.csdn.net/guard_mine/article/details/43056213