UVA 12012 - Detection of Extraterrestrial(KMP)

UVA 12012 - Detection of Extraterrestrial

题目链接

题意:给定一个字符串,求其所有子串中,对应1-n循环次数的最长串长度

思路:KMP,n才1000,可以接受O(n^2)的算法,对于每个后缀串,做一次KMP,然后在遍历一遍KMP数组,这样就可以得到每个子串的所有循环次数了,然后不断更新答案即可

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 1005;

int t, ans[N], n, l, r, m, next[N];
char str[N], s[N];

void getnext() {
    next[0] = next[1] = 0;
    int j = 0;
    for (int i = 2; i <= m; i++) {
	while (j && s[i - 1] != s[j]) j = next[j];
	if (s[i - 1] == s[j]) j++;
	next[i] = j;
    }
}

int main() {
    int cas = 0;
    scanf("%d", &t);
    while (t--) {
	memset(ans, 0, sizeof(ans));
	scanf("%s", str);
	n = strlen(str);
	for (int i = 0; i < n; i++) {
	    m = 0;
	    for (int j = i; j < n; j++)
		s[m++] = str[j];
	    getnext();
	    for (int j = 1; j <= m; j++) {
		int tmp = j;
		while (tmp) {
		    if (j % (j - next[tmp]) == 0) {
			int ti = j / (j - next[tmp]);
			ans[ti] = max(ans[ti], j);
		    }
		    tmp = next[tmp];
		}
	    }
	}
	printf("Case #%d:", ++cas);
	for (int i = 1; i <= n; i++)
	    printf(" %d", ans[i]);
	printf("\n");
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值