还在看后缀数组,罗穗骞神牛的课件真是非常给力。
今天做了场字符串的练习,包括KMP,Trie,AC自动机和后缀数组。
A. Oulipo
貌似是POJ的,以前做过。直接用KMP水过了 。
B. 统计难题
是HDU的吧,题意就是求一些串是另一些串前缀的个数,直接用Trie搞。
struct trie{
int count ;
struct trie *next[26] ;
trie(){
mem(next,0) ;
count = 0 ;
}
} ;
trie *root = 0 ;
void build(char *a){
int l = strlen(a) ;
trie *p = root ;
trie *temp = 0 ;
for (int i = 0 ; i < l ;i ++ ){
int tt = a[i] - 'a' ;
if(p -> next[tt] == 0){
temp = new trie ;
p -> next[tt] = temp ;
}
p = p -> next[tt] ;
p -> count ++ ;
}
}
int search(char *a){
int l = strlen(a) ;
trie *p = root ;
bool flag = 0 ;
for (int i = 0 ; i < l ; i ++ ){
int tt = a[i] - 'a' ;
if(p -> next[tt] == 0){
flag = 1 ;
break ;
}
p = p -> next[tt] ;
}
if(flag)return 0 ;
return p -> count ;
}
int main() {
char a[11111] ;
root = new trie ;
int d = 5 ;
while(gets(a)){
int l = strlen(a) ;
if(!l)break ;
build(a) ;
}
while(cin >> a){
cout << search(a) << endl;
}
return 0 ;
}
C. Keywords Search
HDU的题,我用了三种方法,用N次KMP ,TLE,N棵Trie树,MLE(纯娱乐。。),AC自动机A掉。
题意就是给你一些字符串,问在目标串里面出现了多少次。
AC自动机的学习课件网上很多,我就说下我自己对AC自动机的理解。
其实AC自动机就是KMP+Trie,他的Fail指针是和KMP的next数组一样的作用。
Fail指针是指向当前节点字母的上一次出现该字母的位置,如果没有则指向root。
具体请看神牛博客。神牛博客
//HDU 2222
struct node {
node *fail ;
node *next[26] ;
int count ;
node() {
fail = 0 ;
count = 0 ;
mem(next , 0) ;
}
}*qe[500005] ;
node *root = 0 ;
//insert a[] .
void insert(char *a) {
node *p = root ;
int l = strlen(a) ;
for (int i = 0 ; i < l ; i ++ ) {
int tt = a[i] - 'a' ;
if(p -> next[tt] == 0) {
p -> next[tt] = new node() ;
}
p = p -> next[tt] ;
}
p -> count ++ ;
}
//build *fail .
void build() {
root -> fail = 0 ;
int h = 0 , t = 0 ;
qe[h ++ ] = root ;
while(h > t) {
node *temp = qe[t ++ ] ;
node *p = 0 ;
for (int i = 0 ; i < 26 ; i ++ ) {
if(temp -> next[i] != 0) {
if(temp == root)temp -> next[i] -> fail = root ;
else {
p = temp -> fail ;
while(p != 0) {
if(p -> next[i] != 0) {
temp -> next[i] -> fail = p -> next[i] ;//找到匹配
break ;
}
p = p -> fail ;
}
if(p == 0)temp -> next[i] -> fail = root ;//如果没找到,则将fail指向root
}
qe[h ++ ] = temp -> next[i] ;
}
}
}
}
int search(char *a) {
int l = strlen(a) ;
node *p = root ;
int ans = 0 ;
for (int i = 0 ; i < l ; i ++ ) {
int tt = a[i] - 'a' ;
while(p -> next[tt] == 0 && p != root)p = p -> fail ;
p = p -> next[tt] ;
p = (p == 0) ? root : p ;
node *temp = p ;
while(temp != root && temp -> count != -1) {
ans += temp -> count ;
temp -> count = -1 ;
temp = temp -> fail ;
}
}
return ans ;
}
char aa[55] ;
char bb[1111111] ;
int main() {
int T ;
cin >> T ;
while (T -- ) {
int n ;
root = new node() ;
cin >> n ;
for (int i = 0 ; i < n ; i ++ ) {
scanf("%s",aa) ;
insert(aa) ;
}
build() ;
scanf("%s",bb) ;
cout << search(bb) << endl;
}
return 0 ;
}
题意是给你2个串,问最长公共字串的长度。
后缀数组,正在看罗穗骞神牛的课件。
找两个字符串的最长公共字串的长度。首先将两个字符串连起来,中间用一个没有出现过的字符连接。
然后利用height数组的特性,我们可以找出位于两个不同字符串里的后缀的最大的height。
我们知道height[i] 是 sa[i - 1]和sa[i] 的最长公共前缀。
那么我们只需要找那些sa[i - 1]和sa[i] 位于不同字符串的字串就可以了。
具体判断请看代码。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include