SDUTOJ2828_字典树
生活随笔
收集整理的這篇文章主要介紹了
SDUTOJ2828_字典树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字典樹
Time Limit:?1000 ms?Memory Limit:?65536 KiB
Submit?Statistic
Problem Description
遇到單詞不認識怎么辦? 查字典啊,已知字典中有n個單詞,假設單詞都是由小寫字母組成。現有m個不認識的單詞,詢問這m個單詞是否出現在字典中。
Input
含有多組測試用例。
第一行輸入n,m (n>=0&&n<=100000&&m>=0&&m<=100000)分別是字典中存在的n個單詞和要查詢的m個單詞.
緊跟著n行,代表字典中存在的單詞。
然后m行,要查詢的m個單詞
n=0&&m=0 程序結束
數據保證所有的單詞都是有小寫字母組成,并且長度不超過10
Output
若存在則輸出Yes,不存在輸出No .
Sample Input
3 2 aab aa ad ac ad 0 0Sample Output
No YesHint
Source
gyx
?
#include <bits/stdc++.h> using namespace std; struct tree {int cnt;tree *nextt[26]; }; tree T[1000000]; // 申請靜態內存 int top; tree *creat() // 創建下一代 {tree *p = &T[top++];for (int i = 0; i < 26; i++)p->nextt[i] = NULL;p->cnt = 0;return p; }void insert(tree *root, char *str) // 插入單詞構建字典 {tree *p = root;for (int i = 0; i < strlen(str); i++){int index = str[i] - 'a'; // index 索引字符str[i]在26字母中的順序if (p->nextt[index] != NULL) // 當這一位置已經有了這個字符的時候 進入下一代{p = p->nextt[index]; // 進入判斷下一層index位置是否有元素continue;}else // 當這一位置沒有有這個字符的時候 開辟下一代并存入將此字符當代{p->nextt[index] = creat();p = p->nextt[index];}}p->cnt = 1; // 標記這里存完一個單詞 便于后序查找//return 0; }int search(tree *root, char *str) {tree *p = root;for (int i = 0; i < strlen(str); i++){int index = str[i] - 'a';if (p->nextt[index] != NULL) // 匹配到該字母 進入下一層p = p->nextt[index];else // 匹配不到終止return 0;}/*所有字母都已經匹配到了 判斷是否存在改單詞*/if (p->cnt == 1) // 存在return 1;else // 不存在返回0return 0; } int main() {int n, m;char s[11];while (~scanf("%d %d", &n, &m)){if (m == 0 && n == 0)break;top = 0;tree *root = creat();for (int i = 0; i < n; i++){scanf("%s", s);insert(root, s);}for (int i = 0; i < m; i++){scanf("%s", s);int ans = search(root, s);if (ans == 1)printf("Yes\n");elseprintf("No\n");}}return 0; }?
轉載于:https://www.cnblogs.com/iQXQZX/p/10258769.html
總結
以上是生活随笔為你收集整理的SDUTOJ2828_字典树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3安装后无法使用退格键的问题
- 下一篇: (转)动态Entity Framewor