ACM2015沈阳:B-Bazinga

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
",++num,ans);
	}
}
原文地址:https://www.cnblogs.com/lcxer/p/10315031.html