HDU 2896 只需判斷「是否出現」,本題要求統計 n 個模式串在一個長文本(≤ 2×106)中**各自出現的次數**。
match 函數返回 void,不再提前返回,需掃描完整文本print 遞歸累加 cnt[val[j]]++,計數而非標記SIGMA_SIZE=199(代碼中較大,可改 26)char s[2000000+10] 讀入void match(char *T) {
int n = strlen(T);
int j = 0;
for (int i = 0; i < n; ++i) {
int c = T[i] - 'A'; // 索引映射
while (j && !ch[j][c]) j = fail[j];
j = ch[j][c];
// 輸出鏈表上所有模式串計數++
for (int k = j; k; k = last[k])
if (val[k]) cnt[val[k]]++;
}
}
// 主函數讀入單個長文本,匹配後輸出所有 cnt>0 的模式串及其次數
int main() {
while (cin >> n) {
init();
for (int i = 1; i <= n; ++i) {
cin >> buf[i];
insert(buf[i], i);
}
build_fail();
cin >> s;
match(s);
for (int i = 1; i <= n; ++i)
if (cnt[i]) cout << buf[i] << ": " << cnt[i] << "\n";
}
}
代碼中 for (int k=j; k; k=last[k]) 直接遍歷輸出鏈表,若模式串有包含關係(如 "ABC" 和 "BC"),同一位置會觸發多次計數,**這正是題目要求**(統計每個模式串獨立出現次數)。
string 重複分配cnt 數組大小 ≥ n+1,每次測試用例 memset 清零while(cin>>n) 循環處理