hdu6153 A Secret(KMP + DP)
题意: 给你两个字符串 t 和 s,然后让你计算 s的后缀在 t中出现的次数* 后缀的长度 累加的 和 。 思路: 考虑KMP ,因为 KMP 是匹配前缀的所以,需要倒转字符串。 然后设dp数组为 长度 为 i的前缀 在 t中出现 的次数 ,在 KMP 匹配的过程中,每次 dp[j] ++。但是,KMP算法为了减少 回溯,会省略相同长度字符的匹配,即Next[i] 代表着非前缀 后缀的 子串 与 该字符串前缀 匹配的最大长度,如果Next[i]非零,i 长度的 前缀 必然包含一个长度为Next[i] 的前缀 和 整个字符串的前缀匹配。 即 dp[Next[i]] += dp[i] AC Code: #include<iostream> #include<cstring> #include<queue> #include<map> #include<set> #include<stack> #include<cmath> #include<cstdio> #include<iomanip> #include<sstream> #include<algorithm> using namespace std; #define read(x) scanf("%d",&x) #define Read(x,y) scanf("%d%d",&x,&y) #define sRead(x,y,z)