Problem Description
String matching is a common type of problem in computer science. One string matching problem is as following:

Given a string s[0…len−1], please calculate the length of the longest common prefix of s[i…len−1] and s[0…len−1] for each i>0.

I believe everyone can do it by brute force.
The pseudo code of the brute force approach is as the following:

We are wondering, for any given string, what is the number of compare operations invoked if we use the above algorithm. Please tell us the answer before we attempt to run this algorithm.

 
Input
The first line contains an integer T, denoting the number of test cases.
Each test case contains one string in a line consisting of printable ASCII characters except space.

* 1≤T≤30

* string length ≤106 for every string

 
Output
For each test, print an integer in one line indicating the number of compare operations invoked if we run the algorithm in the statement against the input string.
 
Sample Input
3
_Happy_New_Year_
ywwyww
zjczzzjczjczzzjc
 
Sample Output
17
7
32
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<cmath> const int maxn=1e6+;
typedef long long ll;
using namespace std; ll ans;
void pre_EKMP(char x[],int m,ll next[])
{
next[]=m;
int j=;
while(j+<m&&x[j]==x[j+])
{
j++;
} next[]=j;
int k=;
for(int i=;i<m;i++)
{
int p=next[k]+k-;
int L=next[i-k];
if(i+L<p+)next[i]=L;
else
{
j=max(,p-i+);
while(i+j<m&&x[i+j]==x[j])j++; next[i]=j;
k=i;
}
}
} char str[*maxn];
ll nxt[*maxn];
int main()
{
int T;
cin>>T; while(T--)
{
scanf("%s",str);
int len=strlen(str);
ans=; pre_EKMP(str,len,nxt);
for(int t=;t<len;t++)
{
if(nxt[t]+t<len)
{
ans+=(nxt[t]+);
}
else
{
ans+=(len-t);
}
}
// ll ans=0;
printf("%lld\n",ans);
}
return ;
}

最新文章

  1. POJ 2299 Ultra-QuickSort 线段树
  2. PrototypePattrn(原型模式)
  3. 选中多个&lt;ul&gt;中的第一个&lt;li&gt;方法
  4. 保存配置文件的appSetting
  5. 【BZOJ-1857】传送带 三分套三分
  6. delphi 2007 远程调试
  7. mysql sql技巧篇
  8. Linux环境命令大全
  9. C语言求两个函数中的较大者的MAX函数
  10. CSS和JS标签style属性对照表
  11. Echart..js插件渲染报错 data.length&lt;1?
  12. At-rule | CSS @ 规则
  13. javascript判断值是否undefined
  14. HTML5之Canvas影片广场
  15. Java并发之线程间的协作
  16. 浅谈JavaScript的apply和call语句
  17. 一个模型中有两个外键指向同一张表时,创建迁移模型时报错:“ HINT: Add or change a related_name argument to the definition for &#39;AnswersModel.author&#39; or &#39;AnswersModel.relay_to&#39;.”解决方案
  18. Windows转Linux总结(附带常用Linux命令-LinuxMint)
  19. 用友云开放平台之API网关
  20. Prometheus+AlertManager实现邮件报警

热门文章

  1. python 把多个list合并为dataframe并输出到csv文件
  2. pycharm2020专业版永久激活
  3. asp.net core 3.1多种身份验证方案,cookie和jwt混合认证授权
  4. 014_go语言中的变参函数
  5. java 打印流与commons-IO
  6. vue_如何判断变量是数组还是对象
  7. python基本数据类型(—)
  8. 【面经】超硬核面经,已拿蚂蚁金服Offer!!
  9. MetadataCache更新
  10. Java callback回调