【JZOJ6379】小w与密码(password)

· · 个人记录

题目描述:小w获取了一段密文,这段密文包含两个由小写英文字母构成的字符串 s,t。除了这段密文,小 w 还同时得到关键情报,明文是由这两个字符串的非空前缀拼接而成的。并且,s 串的前缀必须要拼在 t 串前缀的前面。
比如 s=‘aba',t=‘aa’。那么从 s 串中取 ab, t 串中取 a, ‘aba’就是一组可能的密文。 而‘aab’就不是一组可能的密文,因为无论怎么取都无法拼接成这个字符串。
小 w 现在已经得到了密文,即两个字符串 s 和 t,他想要知道按照以上规则,由这两个字符串能够拼接成多少种互不相同的明文。

【数据规模和约定】
对于 10% 的数据, |s|,|t|<=10
对于 20% 的数据, |s|,|t|<=100
对于 50% 的数据, |s|,|t|<=1000
对于 100% 的数据, |s|,|t|<=10^5

这道题可以发现直接做比较困难。而且本人也不会做er hhahahaha

于是这就可以用总方案数减去不合法的方案数。如何不合法?
举个例子:
令si为s的前缀,ti为t的前缀,且长度按i递增。如果有:

不难发现,如果满足上面的等式,那么就一定有$t0$既是后面所有$t$项的前缀,又是所有$t$项的后缀。前缀不用说了,看到前缀就是$KMP$什么的了。 对于当前的一个前缀,其实就是统计它在$s$上出现的次数。 而只要有$KMP$的$p$,那就证明它可以被更小的前缀代替。 然后跑一遍后缀和。相当于把情况压到没有$KMP$的$p$数组的前缀上。 代码: ```cpp #include <cstdio> #include <cstring> using namespace std; const int N = 500010; struct Len{ long long s,t; } len; char s[N],t[N]; long long tot[N],Ans,p[N]; int main() { freopen("password.in","r",stdin); freopen("password.out","w",stdout); scanf(" %s\n",s + 1), scanf(" %s",t + 1); len.s = strlen(s + 1), len.t = strlen(t + 1), Ans = len.t * len.s; for(int i = 2,j = 0;i <= len.t; ++ i) //求p数组 { while(j && t[j + 1] != t[i]) j = p[j]; if(t[i] == t[j + 1]) ++j; p[i] = j; } for(int i = 2,j = 0;i <= len.s; ++ i) //求在s中的出现次数 { while(j && t[j + 1] != s[i]) j = p[j]; if(s[i] == t[j + 1]) ++tot[++j], j = j == len.t ? p[j] : j; } for(int i = len.s;i > 0; -- i) tot[p[i]] += tot[i]; //将答案压到没有p的前缀上 for(int i = 1;i <= len.t; ++ i) Ans -= p[i] ? tot[i - p[i]] : 0; printf("%lld",Ans); fclose(stdin); fclose(stdout); return 0; } ``` 注意开$long long$。不开白忙活一场。