jzoj 5178. 【NOIP2017提高組模擬6.28】So many prefix?(kmp+dp)
阿新 • • 發佈:2018-11-01
5178. 【NOIP2017提高組模擬6.28】So many prefix?
Description
Sample Input
樣例一:
abababc
樣例二:
isdashagayisdashagaydashisnotagaydashisnotagay
Sample Output
樣例一:
6
樣例二:
30
Data Constraint
分析:KMP + DP,考慮 KMP 中的 next[i],代表最大的 k(k != i) 使‘s[1]s[2]…s[k] == s[i – k + 1]s[i –
k]…s[i]’,那麼我們設 f[i] 代表以 i 字首 ‘s[1]s[2]…s[i]’ 內所有偶數子串出現的次數(包含本身),得
到:f[i] = f[i]+f[next[i]]+(i%2==0)
程式碼
#include <cstdio> #include <cstring> #include <string> #define N 300000 using namespace std; int next[N]; char s[N]; int f[N]; void getnext() { int j = 0; int len = strlen(s + 1); for (int i = 2; i <= len; i++) { while (j && s[j + 1] != s[i]) j = next[j]; if (s[j + 1] == s[i]) j++; next[i] = j; } } int main() { scanf("%s", s + 1); int n = strlen(s + 1); getnext(); for (int i = 2; i <= n; i++) { if (i % 2 == 0) f[i]++; f[i] += f[next[i]]; } int ans = 0; for (int i = 2; i <= n; i++) ans += f[i]; printf("%d\n", ans); }