2019.1.24

数据范围:\(n<=500,m<=2000\)

这个题最裸的暴力就是对于每个字符串,都去验证一次,时间复杂度\(O(n^2m)\)

我们发现,如果对于字符串\(i\),前\(i-1\)个字符串都是它的子串,假如存在一个字符串\(j\),使得\(i\)是\(j\)的子串,那么\(j\)就不需要去验证前\(i-1\)个字符串

这样就很好想到,我们对于字符串\(i\),只需要记下\(i-1\)中最后一个不是它子串的字符串,就能将时间复杂度优化到\(O(nm)\)

代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
void read(int &x) {
char ch; bool ok;
for(ok=0,ch=getchar(); !isdigit(ch); ch=getchar()) if(ch=='-') ok=1;
for(x=0; isdigit(ch); x=x*10+ch-'0',ch=getchar()); if(ok) x=-x;
}
const int maxn=2e4+1;
#define rg register
char a[501][maxn];
int T,n,lst[501],nxt[501][maxn],ans,num;
void prepare(int x)
{
int n=strlen(a[x]+1);
for(rg int i=2,j=1;i<=n;i++)
{
while(j&&a[x][j]!=a[x][i])j=nxt[x][j];
if(a[x][j]==a[x][i])nxt[x][i]=j;
j++;
}
}
bool kmp(int x,int y)
{
int n=strlen(a[x]+1),m=strlen(a[y]+1);
for(rg int i=1,j=0;i<=n;i++)
{
while(j&&a[x][i]!=a[y][j+1])j=nxt[y][j];
if(a[x][i]==a[y][j+1])j++;
if(j==m)return 0;
}
return 1;
}
int main()
{
read(T);
while(T--)
{
read(n);ans=-1;
memset(lst,0,sizeof lst);
for(rg int i=1;i<=n;i++)scanf("%s",a[i]+1),prepare(i);
for(rg int i=1;i<=n;i++)
{
for(rg int j=i-1;j;j=lst[j])if(kmp(i,j)){lst[i]=j;break;}
if(lst[i])ans=i;
}
printf("Case #%d: %d\n",++num,ans);
}
}

最新文章

  1. node crypto md5加密,并解决中文不相同的问题
  2. 模板(Template)
  3. jquerymobile,手机端click无效
  4. Sans Serif 与 Serif 字体是什么意思?
  5. SE 2014年4月1日
  6. 第一章 自定义MVC框架
  7. 什么是mybatis 为什么要使用my batis
  8. 【Python3之pymysql模块】
  9. 商城项目回顾整理(二)easyUi数据表格使用
  10. 【洛谷3047】[USACO12FEB]附近的牛Nearby Cows
  11. 关于Maven的配置与学习
  12. [Abp 源码分析]十二、多租户体系与权限验证
  13. 5款Mac极速下载工具推荐和下载
  14. 力扣(LeetCode)804. 唯一摩尔斯密码词
  15. spring部分注解
  16. [SQLSERVER] 把TransactionLog截断
  17. 【第七课】Nginx反向代理和负载均衡
  18. Capterra Software Categories
  19. Java入门与基础算法班 - 课程大纲
  20. API接口测试中需要注意的地方

热门文章

  1. 【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal
  2. 【C++基础学习】数据封装、构造函数
  3. ssh服务配置文件---sshd_config详解
  4. Ext rowcontextmenu回调
  5. 双端队列篇deque SDUT OJ 双向队列
  6. v-for指令用法一
  7. hdu-5724 Chess(组合游戏)
  8. python 基础之第八天--字典相关
  9. liunx目录/etc下相关配置
  10. 转C++的一点点