单词查找树(信息学奥赛一本通-T1337)
生活随笔
收集整理的這篇文章主要介紹了
单词查找树(信息学奥赛一本通-T1337)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目描述】
在進行文法分析的時候,通常需要檢測一個單詞是否在我們的單詞列表里。為了提高查找和定位的速度,通常都畫出與單詞列表所對應的單詞查找樹,其特點如下:
1.根結點不包含字母,除根結點外每一個結點都僅包含一個大寫英文字母;
2.從根結點到某一結點,路徑上經過的字母依次連起來所構成的字母序列,稱為該結點對應的單詞。單詞列表中的每個單詞,都是該單詞查找樹某個結點所對應的單詞;
3.在滿足上述條件下,該單詞查找樹的結點數最少。
4.例如圖3-2左邊的單詞列表就對應于右邊的單詞查找樹。注意,對一個確定的單詞列表,請統計對應的單詞查找樹的結點數(包含根結點)。
【輸入】
為一個單詞列表,每一行僅包含一個單詞和一個換行/回車符。每個單詞僅由大寫的英文字母組成,長度不超過63個字母 。文件總長度不超過32K,至少有一行數據。
【輸出】
僅包含一個整數,該整數為單詞列表對應的單詞查找樹的結點數。
【輸入樣例】
A
AN
ASP
AS
ASC
ASCII
BAS
BASIC
【輸出樣例】
13
【源程序】
#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include<stack> #include<queue> #include<vector> #include<set> #include<map> #include<bitset> #include<unordered_map> #include<unordered_set> #define PI acos(-1.0) #define INF 0x3f3f3f3f #define LL long long #define Pair pair<int,int> LL quickPow(LL a,LL b){ LL res=1; while(b){if(b&1)res*=a; a*=a; b>>=1;} return res; } LL multMod(LL a,LL b,LL mod){ a%=mod; b%=mod; LL res=0; while(b){if(b&1)res=(res+a)%mod; a=(a<<=1)%mod; b>>=1; } return res%mod;} LL quickMultPowMod(LL a, LL b,LL mod){ LL res=1,k=a; while(b){if((b&1))res=multMod(res,k,mod)%mod; k=multMod(k,k,mod)%mod; b>>=1;} return res%mod;} LL quickPowMod(LL a,LL b,LL mod){ LL res=1; while(b){if(b&1)res=(a*res)%mod; a=(a*a)%mod; b>>=1; } return res; } LL getInv(LL a,LL mod){ return quickPowMod(a,mod-2,mod); } LL GCD(LL x,LL y){ return !y?x:GCD(y,x%y); } LL LCM(LL x,LL y){ return x/GCD(x,y)*y; } const double EPS = 1E-6; const int MOD = 1000000000+7; const int N = 1000+5; const int dx[] = {0,0,-1,1,1,-1,1,1}; const int dy[] = {1,-1,0,0,-1,1,-1,1}; using namespace std;char s[N]; int tot=0;//編號 int trie[N][26];//字典樹 int val[N];//字符串結尾標記,val[i]=x表示第i個節點的權值為x void insert(char *s){//插入單詞sint len=strlen(s);//單詞s的長度int root=0;//字典樹上當前匹配到的結點for(int i=0;i<len;i++){int id=s[i]-'A';//子節點編號if(trie[root][id]==0)//如果之前沒有從root到id的前綴 trie[root][id]=++tot;//插入root=trie[root][id];//順著字典樹往下走} } int main(){while(scanf("%s",s)!=EOF)insert(s);printf("%d\n", tot + 1);return 0; }?
總結
以上是生活随笔為你收集整理的单词查找树(信息学奥赛一本通-T1337)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电池的寿命(信息学奥赛一本通-T1229
- 下一篇: 导弹拦截(洛谷-P1020)