【51NOD1304】字符串的相似度
2024-10-08 01:28:02
题目描述
我们定义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;
}
最新文章
- 解决BUG:CS1617: 选项“6”对 /langversion 无效;必须是 ISO-1、ISO-2、3、4、5 或 Default
- split函数的实现
- VS2013快捷键大全
- 代码中access 的使用
- 细化如何安装LNMP + Zabbix 监控安装文档以及故障排除
- jqueryui引用出错(base is not a constructor,widget no found)
- [转载] #define new DEBUG_NEW
- ArrayList中元素去重问题
- jquery1.8在ie8下not无效?
- 洛谷 P1169 [ZJOI2007]棋盘制作
- WTL 自定义 Button类-自绘
- 1-5html文件基本结构
- [原]使用MachOView辅助破解AppStore应用
- Python基础学习1---函数
- linux(九)之网络基础
- Python: The _imagingft C module is not installed错误的解决
- Android Foreground Service (前台服务)
- HihoCoder - 1038 01背包 动态规划
- 简述at和crontab命令
- jQuery的html和css
热门文章
- C++项目使用的开源库记录
- Spring AOP(一)--基本概念
- Java内功修炼系列一反射
- Jmeter设置中文汉化
- 跟我一起了解koa(一)
- 移动端页面输入法挡住input输入框的解决方法
- 转var,let,const,js严格模式的详解
- 手残,盘符前边多打一个空格导致的message d:\WEB_APP_QuChongFu\file\五月.xlsx (文件名、目录名或卷标语法不正确。)
- Python之路,Day3- Python基础(转载Alex)
- centos 安装redis2.8.9