数据太水-错误错误AC-警示后人
查看原帖
数据太水-错误错误AC-警示后人
929561
lividream楼主2023/7/14 16:39

下面代码中,删去被注释调之处,实测AC

hack数据

11

a b aa aa ab bc bd aaa aac aaad aaae

oaaabcd

测试输出

0

正确输出

7

代码

#include<bits/stdc++.h>
using namespace std;
int read(){
	int res=0;
	bool f=false;
	char ch=getchar();
	while(!isdigit(ch)){
		if(ch=='-') f=true;
		ch=getchar();
	}
	while(isdigit(ch)){
		res=(res<<1)+(res<<3)+(ch^48);
		ch=getchar();
	}
	if(f) return -res;
	return res;
}
int const N=1e6+1;
class Aho_Corasick_Automaton{
 private:
 	
	int tot=1;
	const int root=1;
	int trie[N][26];
	int fail[N],cnt[N];
	
 public:
 	
 	void insert(string s){ 
 		int p=root;
 		for(int i=0;i<s.length();++i){
 			int ch = s[i]-'a';
 			if(!trie[p][ch]) trie[p][ch]=++tot;
			p = trie[p][ch] ;  
		}
		cnt[p]+=1;
	}
	
	void matching_fail(){
		queue<int> que;
		for(int i=0;i<26;++i){
			if(trie[root][i]){
				fail[trie[root][i]] = root;
				que.push(trie[1][i]);
			}
//			else
//				trie[root][i] = root;
		}
		while(!que.empty()){
			int t=que.front();
			que.pop();
			for(int i=0;i<26;++i){
				if(trie[t][i]){
					fail[trie[t][i]] = trie[fail[t]][i];
					que.push(trie[t][i]);
				}
				else 
					trie[t][i] = trie[fail[t]][i];
			}
		}
	}
	
	int get_query(string s){
		int p=root,ans=0;
		for(int i=0;i<s.length();++i){
			p = trie[p][s[i]-'a'];
			for(int t=p;t!=root and cnt[t]!=-1;t=fail[t]){
				ans += cnt[t];
				cnt[t] = -1;
			}
		}	
		return ans;
	}
}AC;
signed main(){
	int n = read();
	for(int i=1;i<=n;++i){
		string s;
		cin>>s;
		AC.insert(s);
	}
	AC.matching_fail();
	string T;
	cin>>T;
	cout<<AC.get_query(T);
}


2023/7/14 16:39
加载中...