HDU 1251 统计难题(Trie模版题)
生活随笔
收集整理的這篇文章主要介紹了
HDU 1251 统计难题(Trie模版题)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
統計難題
Time Limit: 4000/2000 MS (Java/Others)????Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 34909????Accepted Submission(s): 13109
?
Input 輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.注意:本題只有一組測試數據,處理到文件結束.
?
Output 對于每個提問,給出以該字符串為前綴的單詞的數量.?
Sample Input banana band bee absolute acm ba b band abc?
Sample Output 2 3 1 0?
題目鏈接:HDU 1251
以前以為很高級的數據結構,原來就是一個很多后繼節點的鏈表而已,建立過程很簡單明了,不懂的話畫一個多叉樹就知道了……,每一次從表頭*root(最近學的是鏈表,就用*L好了)開始找,然后如果存在就繼續找直到遍歷完字符串,插入和查找都是這個原理還有最好別用G++提交容易爆內存,C++就不會了
代碼:
#include <stdio.h> #include <iostream> #include <algorithm> #include <cstdlib> #include <sstream> #include <cstring> #include <bitset> #include <string> #include <deque> #include <stack> #include <cmath> #include <queue> #include <set> #include <map> using namespace std; #define INF 0x3f3f3f3f #define CLR(x,y) memset(x,y,sizeof(x)) #define LC(x) (x<<1) #define RC(x) ((x<<1)+1) #define MID(x,y) ((x+y)>>1) typedef pair<int,int> pii; typedef long long LL; const double PI=acos(-1.0); const int N=26; const int M=15; struct Trie {Trie *nxt[N];int cnt;Trie(){CLR(nxt,0);cnt=0;} }; Trie *L=new Trie(); void update(char s[]) {int len=strlen(s);int indx;Trie *cur=L;for (int i=0; i<len; ++i){indx=s[i]-'a';if(cur->nxt[indx]){cur=cur->nxt[indx];++(cur->cnt);}else{Trie *one=new Trie();++(one->cnt);cur->nxt[indx]=one;cur=cur->nxt[indx];///新建之后還是要跳到這個新建節點的}} } int Find(char s[]) {int len=strlen(s);Trie *cur=L;int indx;for(int i=0; i<len; ++i){indx=s[i]-'a';if(!cur->nxt[indx])return 0;cur=cur->nxt[indx];}return cur->cnt; } char s[M]; int main(void) {while (gets(s)&&strcmp(s,""))update(s);while (gets(s))printf("%d\n",Find(s));return 0; }轉載于:https://www.cnblogs.com/Blackops/p/5904583.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的HDU 1251 统计难题(Trie模版题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FF14 Anamnesis 使用教程
- 下一篇: fastjson 1.2 版本之前的bu