zoukankan      html  css  js  c++  java
  • BZOJ1511: [POI2006]OKR-Periods of Words

    看到题目的要求,有一个特别 naive 的想法:f[i] 表示 从 i 往前跳不为零的 nxt,直到不能跳,能跳到的位置

    然后各种乱搞判断什么的

    其实不用

    考虑一下 kmp 的基本定义

    对于 i 这个前缀,f[i] 这个前缀是它的一个后缀

    你把它放在后缀的位置上一看,这不就是题目要求的吗


    代码:

    #include<algorithm>
    #include<iostream>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<cstdio>
    using namespace std;
    
    typedef long long ll;
    const int MAXN = 1000005;
    
    int n;
    int nxt[MAXN], f[MAXN];
    char str[MAXN];
    ll ans;
    
    inline void getnxt() {
    	nxt[0] = nxt[1] = 0;
    	for(int i = 1; i < n; ++i) {
    		int j = nxt[i];
    		while(j && str[i] != str[j]) j = nxt[j];
    		nxt[i + 1] = (str[i] == str[j]) ? j + 1 : 0;
    	}
    	return;
    }
    
    int main() {
    	scanf("%d", &n); scanf("%s", str);
    	getnxt();
    	for(int i = 1; i <= n; ++i) {
    		f[i] = f[nxt[i]] ? f[nxt[i]] : nxt[i];
    		if(f[i]) ans += i - f[i];
    	}
    	printf("%lld
    ", ans);
    	return 0;
    }
    

      

    禁止诸如开发者知识库/布布扣/码迷/学步园/马开东等 copy 他人博文乃至博客的网站转载 ,用户转载请注明出处:https://www.cnblogs.com/xcysblog/
  • 相关阅读:
    几个数之和----数组刷题
    单调栈刷题
    腾讯金融科技凉经
    mysql刷题
    链表类题目常用方法
    阿里云一面凉经
    腾讯TEG一面凉经
    腾讯软件开发-后台开发实习生-一面凉经
    剑指 Offer 19. 正则表达式匹配
    剑指 Offer 20. 表示数值的字符串
  • 原文地址:https://www.cnblogs.com/xcysblog/p/9602471.html
Copyright © 2011-2022 走看看