hdu3746 Cyclic Nacklace(kmp找循环节)

在kmp中循环节的长度是len - nxt[len],len是指串的长度。

需要添加的字符长度应该是len - next[len] - len % (len - next[len]);

const int maxn = 1e5 + 74;
char s[maxn];
int n, nxt[maxn];
inline void getNxt() {
	int slen = strlen(s);
	int i = 0, j = -1;
	nxt[0] = -1;
	while(i < slen) {
		if (j == -1 || s[i] == s[j]) nxt[++i] = ++j;
		else j = nxt[j];
	}
}
int main()
{	
	// freopen("in.txt","r",stdin);
	// freopen("out.txt","w",stdout);
	scanf("%d",&n);
	while(n--) {
		scanf("%s",s);
		int slen = strlen(s);
		getNxt();
		if (nxt[slen] == 0) printf("%d\n", slen);
		else {
			int k = slen - nxt[slen];
			if (slen % k == 0) printf("0\n");
			else printf("%d\n", k - (slen - (slen/k)*k));
		}
	}
	return 0;
}


你可能感兴趣的:(KMP)