HDU - 1251 统计难题(字典树)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 1251 统计难题(字典树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一些單詞,后續再給出一些前綴,詢問包含此前綴的單詞一共有多少個
題目分析:這個題目的數據可能有點水,而且時間給的也很足,給了兩秒,而且加上是hdu的,可以用無序map亂搞,訓練的時候我直接亂搞了一發就過了。。不過事后肯定是會補題的,今天學習了字典樹之后再看這個題就是一個字典樹的板子題啦,加上他直接詢問的是前綴,字典樹還有一個名字就叫前綴樹,直接把板子掛上,然后color數組(用來記錄某個單詞是否出現過)就可以不用了,取而代之的是一個dp數組用來記錄每一個前綴出現的次數即可,時間復雜度我不太會算,不過可以確定的是用起來確實比stl要快多了,十倍的時間是可以省出來的,直接上代碼吧:
#include<iostream> #include<cstdlib> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<climits> #include<cmath> #include<cctype> #include<stack> #include<queue> #include<list> #include<vector> #include<set> #include<map> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e6+100;int k=1;int trie[N][26];int dp[N];void insert(char s[]) {int len=strlen(s);int pos=0;for(int i=0;i<len;i++){int to=s[i]-'a';if(!trie[pos][to])trie[pos][to]=k++;pos=trie[pos][to];dp[pos]++;} }int search(char s[]) {int len=strlen(s);int pos=0;for(int i=0;i<len;i++){int to=s[i]-'a';if(!trie[pos][to])return 0;pos=trie[pos][to];}return dp[pos]; }int main() { // freopen("input.txt","r",stdin);char s[15];while(gets(s)&&s[0])insert(s);while(scanf("%s",s)!=EOF)printf("%d\n",search(s));return 0; }?
總結
以上是生活随笔為你收集整理的HDU - 1251 统计难题(字典树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU - 3746 Cyclic Na
- 下一篇: POJ - 3630 Phone Lis