Clannad 18四川省赛【AC自动机+DP】

题目链接
第一次遇到卡last优化的题。
因为要不断跳fail链上的ed节点,不用last优化的话会T。
因为fail指针指向的是当前节点的最长后缀,所以用dp[i]表示前i个字符能分解的数量,转移方程就为
dp[i] += dp[i-size[u]] (u是fail链上的所有节点)
所以要last优化。。。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+5;
char s[maxn];
char ss[maxn];
long long dp[maxn];
const long long mod = 1e9+7;
struct AC{
	int nex[maxn][26], root, tot;
	int ed[maxn], size[maxn], f[maxn], last[maxn];
	int newnode() {
		for(int i = 0; i < 26; i++) {
			nex[tot][i] = -1;
		}
		last[tot] = ed[tot] = size[tot] = 0;
		return tot++;
	}
	void init() {
		tot = 0;
		root = newnode();
	}
	void insert(char *s, int x) {
		int u = root;
		for(int i = 0; i < x; i++) {
			int ch = s[i]-'a';
			if(nex[u][ch] == -1) nex[u][ch] = newnode();
			u = nex[u][ch];
		}
		ed[u] = 1;
		size[u] = x;
	}
	void getfail() {
		queue<int>Q;
		for(int i = 0; i < 26; i++) {
			if(nex[root][i] == -1) nex[root][i] = root;
			else {
				f[nex[root][i]] = root;
				Q.push(nex[root][i]);
				last[nex[root][i]] = root;
			}
		}
		while(!Q.empty()) {
			int u = Q.front();Q.pop();
			for(int i = 0; i < 26; i++) {
				if(nex[u][i] == -1) nex[u][i] = nex[f[u]][i];
				else {
					f[nex[u][i]] = nex[f[u]][i];
					Q.push(nex[u][i]);
					last[nex[u][i]] = ed[f[nex[u][i]]]?f[nex[u][i]]:last[f[nex[u][i]]];
				}
			}
		}
	}
	void query(char *s) {
		int len = strlen(s), u = root;
		dp[0] = 1;
		for(int i = 0; i < len; i++) {
			u = nex[u][s[i]-'a'];
			int t = u;
			while(t != root) {
					dp[i+1] += dp[i+1-size[t]], dp[i+1] %= mod;
				t = last[t];
			}
		}
		for(int i = 1; i <= len; i++) {
			printf("%lld%c", dp[i], i==len?'\n':' ');
		}
	}
}ac;
void solve() {
	int n, m;scanf("%d%d%s", &n, &m, s);
	ac.init();
	for(int i = 0; i <= n; i++) dp[i] = 0;
	for(int i = 1; i <= m; i++) {
		scanf("%s", ss);
		ac.insert(ss, strlen(ss));
	}
	ac.getfail();
	ac.query(s);
}
int main() {
	int Case = 1;
	scanf("%d", &Case);
	while(Case--) {
		solve();
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值