要學會ac自己主動機,我們必須知道什麼是trie。也就是字典樹。最好對kmp演算法也有些了解。trie樹和kmp演算法我之前部落格都有寫過。感興趣的能夠看看。
簡單敘述下問題,如今給出
"hsay";
"ah";
"sahe";
"he";
"say";
"herhb";
"aher";
"erhs"
答案是7。
這就是乙個多模式匹配問題。
ac自己主動機演算法分為3步:構造一棵trie樹。構造失敗指標和模式匹配過程。
失敗指標和kmp演算法中的next函式或稱shift函式的功能類似。
上**釋了失敗指標的作用。
// ac_automachine.cpp : 定義控制台應用程式的入口點。
//#include "stdafx.h"
#include#include#include#includeusing namespace std;
#define maxsize 26
struct trienode
;setre;//儲存結果
trienode*initiate_trie()
bool search(trienode*root, char*str)
if (tn->isword == false)
return false;
return true;
}trienode*build_trie_singleword(trienode*root, char*str)
tn->next[k]->p = *str;
tn->next[k]->num = 1;
tn->next[k]->parent = tn;
tn->next[k]->isword = false;
} else
tn = tn->next[k];
str++;
} tn->isword = true;
return root;
}void initiate_fail_pointer(trienode*root, trienode*node)
else
n = n->parent;
} for (int i = 0; i < maxsize; i++)
if (node->next[i] != null)
initiate_fail_pointer(root, node->next[i]); }}
int ac_automachine(trienode*root, char*str)
trienode*p,*node = root->next[str[k] - 'a'];
p = null;
while (node != null)
std::reverse(aa.begin(), aa.end());
if (re.find(aa) == re.end())
}if (!node->fail.empty())
std::reverse(aa.begin(), aa.end());
if (re.find(aa) == re.end())}}
k++;
p = node;
node = node->next[str[k] - 'a'];
} k--;
node = p;
_assert(node);
if (node->fail.empty())
else
std::reverse(aa.begin(), aa.end());
if (re.find(aa) == re.end())
}if (!tp->fail.empty())
std::reverse(aa.begin(), aa.end());
if (re.find(aa) == re.end())}}
kk++;
p = tp;
tp = tp->next[str[k + kk] - 'a'];
}if (kk > max)
}if (!tn->fail.empty())
if (kkk > maxlen)
maxlen = kkk;
}k = k + kk - maxlen;
}else
}//end of else
} return count;
}int _tmain(int argc, _tchar* ar**)
HDU 2896 病毒侵襲 AC自己主動機題解
本題是在text裡面查詢key word的增強版。由於這裡有多個text。那麼就不能夠簡單把trie的葉子標誌記錄改動成 1進行加速了,能夠使用其它技術。我直接使用個vis陣列記錄已經訪問過的節點,達到加速效果,速度還算挺快的。只是看discuss裡面有人直接使用trie,做出了140ms的速度,並...
AC自動機 建立nlogn個AC自動機
string set queries 題意 給你3種操作,1 加入乙個串到集合中。2 刪除集合中的某乙個串 3 查詢集合中的字串在給定的字串種出現幾次。同乙個串可重複 解法 建立多個ac自動機,用二進位制分組來處理。加入給你21個串 分為 16 4 1,再新增乙個串的時候,即21 1,22 16 4...
AC自動機演算法
ac自動機簡介 首先簡要介紹一下ac自動機 aho corasickautomation,該演算法在1975年產生於貝爾實驗室,是著名的多模匹配演算法之一。乙個常見的例子就是給出n個單詞,再給出一段包含m個字元的文章,讓你找出有多少個單詞在文章裡出現過。要搞懂ac自動機,先得有字典樹trie和kmp...