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