[HDOJ 2243] 考研路茫茫——单词情结 [AC自动机+动态规划+矩阵加速]

69 篇文章 0 订阅
26 篇文章 0 订阅

给至多6个字符串,每个长度不超过5,问长度不超过L(L<2^31)的字符串中,有多少个有以这些字符串中至少一个为子串。

先建立AC自动机,然后构造状态转移矩阵,然后用矩阵加速计算。

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int K=26;
const int N=40;
struct Node {
	Node *ch[K],*fail;
	int match,count;
	Node () {
		memset(this,0,sizeof(Node));
	}
	void *operator new(size_t,void *p) {
		return p;
	}
};
Node *que[N];
Node b[N],*root,*superRoot,*bp;
void clear() {
	bp=b;
	superRoot=new(bp++)Node();
	root=new(bp++)Node();
	root->fail=superRoot;
	for (int i=0;i<K;i++) superRoot->ch[i]=root;
	superRoot->match=-1;
}
void insert(char *s) {
	Node *t=root;
	for (;*s;s++) {
		int x=*s-'a';
		if (t->ch[x]==NULL) t->ch[x]=new(bp++)Node();
		t=t->ch[x];
	}
	t->match++;
}
void build() {
	int p=0,q=0;
	que[q++]=root;
	while (p!=q) {
		Node *t=que[p++];
		if (t!=root) t->match+=t->fail->match;
		for (int i=0;i<K;i++) {
			if (t->ch[i]) {
				t->ch[i]->fail=t->fail->ch[i];
				que[q++]=t->ch[i];
			} else t->ch[i]=t->fail->ch[i];
		}
	}
}

struct Matrix {
	int n;
	unsigned long long a[40][40];
	Matrix (int nn=0) {
		n=nn;
		memset(a,0,sizeof(a));
	}
	friend Matrix operator * (const Matrix &a,const Matrix &b) {
		Matrix c;
		int n=c.n=a.n;
		for (int i=0;i<n;i++) 
			for (int j=0;j<n;j++) 
				for (int k=0;k<n;k++)
					c.a[i][j]+=a.a[i][k]*b.a[k][j];
		return c;
	}
};
Matrix pow(const Matrix &x,int n) {
	if (n==1) return x;
	Matrix ans=pow(x,n>>1);
	ans=ans*ans;
	if (n&1) ans=ans*x;
	return ans;
}

int n,l,m;
char s[10];
Matrix c,ans;

void constructMatrix() {
	c=Matrix();
	c.a[0][0]=1;
	c.a[0][1]=1;
	c.a[1][1]=K;
	m=2;
	for (Node *t=root;t!=bp;t++) if (!t->match) t->count=m++;
	for (Node *t=root;t!=bp;t++) 
		if (!t->match)
			for (int k=0;k<K;k++)
				if (t->ch[k]->match) c.a[1][t->count]++;
				else c.a[t->ch[k]->count][t->count]++;
	c.n=m;
	//for (int i=0;i<m;i++) {
		//for (int j=0;j<m;j++) printf("%llu ",c.a[i][j]);
		//printf("\n");
	//}
}

int main() {
	int i;
	while (scanf("%d%d",&n,&l)!=EOF) {
		clear();
		for (i=0;i<n;i++) {
			scanf("%s",s);
			insert(s);
		}
		build();
		constructMatrix();
		ans=pow(c,l);
		printf("%llu\n",ans.a[0][2]+ans.a[1][2]);
	}
	return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值