跳到正文

题解

P3808 AC 自动机(简单版)

Null_in_null约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月17日
篇幅
约 3 分钟
题目
P3808

版本

  1. v1当前

题解:P3808 AC 自动机(简单版)

裸写裸题

C++
#include<cstdio>
#include<cstring>
#include<queue>

using namespace std ;
// #define int long long
#define endl '\n'
#define IOS ios::sync_with_stdio(0) ; cin.tie(0) ; cout.tie(0) ;
const int N = 1e6+5 , M = 1e6+5 , L = 1e6+5 ;

int ch[N][30] , id , cnt[N] ;
int ne [N] ;
queue<int> q ;
char s[M] , w[L] ;
int len , n ;

void insert() {
	int p = 0 ;
	len = strlen(w) ;
	for ( int i = 0 ; i < len ; i++ ) {
		int x = w[i]-'a' ;
		if ( !ch[p][x] ) {
			ch[p][x] = ++id ;
		}
		p = ch[p][x] ;
	}
	cnt[p]++ ;
}

void bfs() {
	for ( int i = 0 ; i < 26 ; i++ )if ( ch[0][i] )q.push(ch[0][i]) ;
	while(q.size()) {
		int f = q.front() ;
		for ( int i = 0 ; i < 26 ; i++ )
			if ( ch[f][i] ) {
				int c = ch[f][i] ;
				int j = ne[f] ;
				while (j&&(!ch[j][i]))j = ne[j] ;
				if ( ch[j][i] )j = ch[j][i] ;
				ne[c] = j ;
				q.push(c) ;
			}
		q.pop() ;
	}
}

signed main() {
	// IOS
	// int T ;
	// cin >> T ;
	// while ( T-- ) {
		// memset(ch,0,sizeof(ch)) ;
		// memset(cnt,0,sizeof(cnt)) ;
		// memset(ne,0,sizeof(ne)) ;
		// id = 0 ;
		scanf("%d",&n) ;
		while ( n-- ) {
			scanf("%s",w) ;
			insert() ;
		}
		bfs() ;
		scanf("%s",s) ;
		len = strlen(s) ;
		int res = 0 ;
		for ( int i = 0 , j = 0 ; i < len ; i++ ) {
			int x = s[i]-'a' ;
			while (j&&(!ch[j][x]))j = ne[j] ;
			if ( ch[j][x] )j = ch[j][x] ;
			int p = j ;
			// while (p){
				res += cnt[p] ;
				cnt[p] = 0 ;
				// p = ne[p] ;
			// }
		}
		printf("%d\n",res) ;
	// }
	return 0 ;
}
原文