其实很简单,只要对KMP的next数组的含义能理解的话,就没有问题了。
/* * hdu3746/win.cpp * Created on: 2012-8-2 * Author : ben */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <map> #include <stack> #include <string> #include <vector> #include <deque> #include <list> #include <functional> #include <numeric> #include <cctype> using namespace std; const int MAX_LEN = 200010; char pattern[MAX_LEN]; int next[MAX_LEN], parlen; void getnext() { int i = 0, j = -1; next[0] = -1; while (i <= parlen) { if (j < 0 || pattern[i] == pattern[j]) { i++; j++; next[i] = j; } else { j = next[j]; } } } int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); #endif int T, ans; scanf("%d", &T); while(T--) { scanf("%s", pattern); parlen = strlen(pattern); getnext(); int ret = next[parlen]; if(ret > parlen / 2) { int xhj = parlen - ret; ans = (xhj - parlen % xhj) % xhj; }else { ans = parlen - ret * 2; } printf("%d\n", ans); } return 0; }