2021牛客寒假第四场 九峰与子序列(dp+哈希)

题目链接:点击这里

题目大意:
给定 n n n 个字符串 a i a_i ai ,一个字符串 s s s ,求用 n n n 个字符串组成字符串 s s s 的方案数

题目大意:
容易想到可以用子序列相关的状态来维护 d p dp dp
d p [ i ] [ j ] dp[i][j] dp[i][j] 表示前 i i i 个串匹配了 s s s 串的前 j j j 个字符,故有转移方程:
d p [ i ] [ j ] = ∑ ( d p [ i − 1 ] [ j − l e n ] ∗ [ a i = = s . s u b s t r ( j − l e n + 1 , j ) ] ) dp[i][j]= \sum (dp[i-1][j-len]*[a_i==s.substr(j-len+1,j)]) dp[i][j]=(dp[i1][jlen][ai==s.substr(jlen+1,j)])
此时问题就转变成了如何快速判断 a i a_i ai s s s 的子序列是否相同,此处用的字符串单哈希来判断(不用双哈希是因为有点卡内存,我直接 m l e mle mle),我们直接提前处理出 a i a_i ai 对应的哈希值,然后边枚举 s s s 的位置边判断转移即可
还要注意,此题不可以直接开 n ∗ ∑ l e n a i n*\sum len_{a_i} nlenai 的数组,我们发现转移只在 i − 1 i-1 i1 层向 i i i 层转移,因此可以使用类似 01 01 01 背包的优化技巧:通过倒序枚举来滚掉第一维
时间复杂度为 O ( n ∑ l e n a i ) O(n\sum len_{a_i}) O(nlenai)

具体细节见代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#define ll long long
#define ull unsigned ll
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
//#define int ll
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 5e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
const int base = 131;
const int base2 = 233;
int n,len[maxn],dp[maxn];
ull p[maxn],sum[maxn],a[maxn];
char s[maxn],ss[maxn];
ull get_hash(int l,int r)
{
	return sum[r]-sum[l-1]*p[r-l+1];
}
signed main()
{
	n = read(); scanf("%s",s+1);
	p[0] = 1;int l = strlen(s+1);
	for(int i = 1;i <= l;i++)
	{
		p[i] = p[i-1]*base;
		sum[i] = sum[i-1]*base+s[i];
	}
	for(int i = 1;i <= n;i++) 
	{
		scanf("%s",ss+1);
		len[i] = strlen(ss+1);
		for(int j = 1;j <= len[i];j++) 
			a[i] = a[i]*base+ss[j];
	}
	dp[0] = 1;
	for(int i = 1;i <= n;i++)
		for(int j = l;j >= len[i];j--)
			if(a[i] == get_hash(j-len[i]+1,j))
				dp[j] += dp[j-len[i]];
	printf("%d\n",dp[l]);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值