zoukankan      html  css  js  c++  java
  • HUST 1328 String (字符串前缀子串个数 --- KMP)

    题意

    给定一个字符串S,定义子串subS[i] = S[0..i],定义C[i]为S中subS[i]的数量,求sigma(C[i])(0<=i<N)。

    思路

    我们以子串结尾的位置来划分阶段求解,即,设ans[i]表示以第i个字符为结尾的子串的个数,则res = sigma(ans[i])。 那么我们怎么求出以某个位置为结尾的字符串中有多少是subS[i]呢? 考虑subS[i]就是S的N个前缀,而以某个位置为结尾又是后缀,所以我们自然要想到利用next数组---前缀后缀对称来解决这个问题。 由next[i]=j表示S[1...j] = S[i-j+1...i]可知,以i为结尾的子串中包含subS[j]本身,并且,它一定还包含subS[j]所包含的前缀。所以ans[i] = ans[j]+1。 最后再加上以i为结尾的子串它本身(上面计算时并没有包括它本身)。

    代码

      [cpp] #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <set> #include <stack> #include <queue> #define MID(x,y) ((x+y)/2) #define MEM(a,b) memset(a,b,sizeof(a)) #define REP(i, begin, end) for (int i = begin; i <= end; i ++) using namespace std; char s[100005]; long long next[100005], res[100005], ans; long long cal_res(int j){ if (next[j] == -1) return 0; else if (~res[j]){ return res[j]; } else{ res[j] = cal_res(next[j]) + 1; return res[j]; } } void get_next(){ int len = strlen(s), j = -1; ans = len; next[0] = -1; for (int i = 1; i < len; i ++){ while(j > -1 && s[i] != s[j+1]) j = next[j]; if (s[i] == s[j+1]) j ++; next[i] = j; ans += cal_res(i); } } int main(){ int t; scanf("%d", &t); while(t --){ MEM(s, 0); MEM(res, -1); scanf("%s", s); get_next(); printf("%lld ", ans); } return 0; } [/cpp]
  • 相关阅读:
    PHP面向对象----- 类的自动加载
    PHP基础知识------页面静态化
    Laravel 开发环境搭建
    jenkins相关学习
    markdown语法学习强化
    bind 使用和配置记录
    关于整形和浮点型的格式输出
    函数体中定义的结构体和类型
    Volatile & Memory Barrier
    各种简单排序算法模版
  • 原文地址:https://www.cnblogs.com/AbandonZHANG/p/4114333.html
Copyright © 2011-2022 走看看