题目描述

我们定义2个字符串的相似度等于两个串的相同前缀的长度。例如 “abc” 同 “abd” 的相似度为2,”aaa” 同 “aaab” 的相似度为3。

给出一个字符串S,计算S同他所有后缀的相似度之和。例如:S = “ababaa”,所有后缀为:

ababaa 6

babaa 0

abaa 3

baa 0

aa 1

a 1

S同所有后缀的相似度的和 = 6 + 0 + 3 + 0 + 1 + 1 = 11

数据范围

1 <= L <= 1000000

=w=

原题求的是每个后缀与整个字符串的最长公共前缀的长度。

也即扩展KMP的next数组的值之和。

代码

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#define ll long long
using namespace std;
const char* fin="ex1304.in";
const char* fout="ex1304.out";
const int inf=0x7fffffff;
const int maxn=1000007;
int n,i,j,k,limit,id;
ll ans;
char a[maxn];
int ne[maxn];
int main(){
scanf("%s",a+1);
n=strlen(a+1);
limit=0;
id=0;
ne[1]=n;
for (i=2;i<=n;i++){
j=ne[i-id+1];
if (i+j-1<limit) ne[i]=j;
else{
j=max(0,limit-i+1);
for (;j+i<=n;j++) if (a[i+j]!=a[j+1]) break;
if (i+j-1>limit){
limit=i+j-1;
id=i;
}
ne[i]=j;
}
}
for (i=1;i<=n;i++) ans+=ne[i];
printf("%lld",ans);
return 0;
}

最新文章

  1. 解决BUG:CS1617: 选项“6”对 /langversion 无效;必须是 ISO-1、ISO-2、3、4、5 或 Default
  2. split函数的实现
  3. VS2013快捷键大全
  4. 代码中access 的使用
  5. 细化如何安装LNMP + Zabbix 监控安装文档以及故障排除
  6. jqueryui引用出错(base is not a constructor,widget no found)
  7. [转载] #define new DEBUG_NEW
  8. ArrayList中元素去重问题
  9. jquery1.8在ie8下not无效?
  10. 洛谷 P1169 [ZJOI2007]棋盘制作
  11. WTL 自定义 Button类-自绘
  12. 1-5html文件基本结构
  13. [原]使用MachOView辅助破解AppStore应用
  14. Python基础学习1---函数
  15. linux(九)之网络基础
  16. Python: The _imagingft C module is not installed错误的解决
  17. Android Foreground Service (前台服务)
  18. HihoCoder - 1038 01背包 动态规划
  19. 简述at和crontab命令
  20. jQuery的html和css

热门文章

  1. C++项目使用的开源库记录
  2. Spring AOP(一)--基本概念
  3. Java内功修炼系列一反射
  4. Jmeter设置中文汉化
  5. 跟我一起了解koa(一)
  6. 移动端页面输入法挡住input输入框的解决方法
  7. 转var,let,const,js严格模式的详解
  8. 手残,盘符前边多打一个空格导致的message d:\WEB_APP_QuChongFu\file\五月.xlsx (文件名、目录名或卷标语法不正确。)
  9. Python之路,Day3- Python基础(转载Alex)
  10. centos 安装redis2.8.9