hdu1251 hash或者字典树
生活随笔
收集整理的這篇文章主要介紹了
hdu1251 hash或者字典树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
統計難題
Problem Description
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重復的單詞出現),現在老師要他統計出以某個字符串為前綴的單詞數量(單詞本身也是自己的前綴).
Input
輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.注意:本題只有一組測試數據,處理到文件結束.
Output
對于每個提問,給出以該字符串為前綴的單詞的數量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
?
Sample Output
2
3
1
0
思路: ?
統計難題
Problem Description
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重復的單詞出現),現在老師要他統計出以某個字符串為前綴的單詞數量(單詞本身也是自己的前綴).
Input
輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.注意:本題只有一組測試數據,處理到文件結束.
Output
對于每個提問,給出以該字符串為前綴的單詞的數量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
?
Sample Output
2
3
1
0
思路: ?
? ? ? 兩種做法,一個是hash就是把每個給定的串拆成len個串,然后hash[now_str]?++ ,在詢問的時候直接輸出hash[str]就行了,這里的hash我用容器實的,map<string?,int>,或者這個題目可以用字典樹實現,字典樹實現也很簡單,就是基本的在每個節點上記錄當前這個節點出現了多少次,然后查找就行了。下面給出兩個方法的代碼。
hash
#include<stdio.h> #include<string.h> #include<string> #include<map> using namespace std;char str[15]; map<string ,int>my_map;int main () {my_map.clear();while(gets(str) ,strlen(str)){int i ,l = strlen(str);char temp[15];for(i = 0 ;i < l ;i ++){temp[i] = str[i];temp[i+1] = '\0';my_map[temp]++;} }while(gets(str)){printf("%d\n" ,my_map[str]);}return 0; }
字典樹
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Tree {Tree *next[26];int v; }Tree;Tree root;void Buid_Tree(char *str) {int len = strlen(str);Tree *p = &root ,*q;for(int i = 0 ;i < len ;i ++){int id = str[i] - 'a';if(p -> next[id] == NULL){q = (Tree *) malloc(sizeof(root));q -> v = 1;for(int j = 0 ;j < 26 ;j ++)q -> next[j] = NULL;p -> next[id] = q;p = p -> next[id];}else{p -> next[id] -> v ++;p = p -> next[id];}} }int Find(char *str) {int len = strlen(str);Tree *p = &root;for(int i = 0 ;i < len ;i ++){int id = str[i] - 'a';p = p -> next[id];if(p == NULL) return 0;}return p -> v; }int main () {char str[15];for(int i = 0 ;i < 26 ;i ++)root.next[i] = NULL;while(gets(str) && str[0] != '\0'){Buid_Tree(str);}while(~scanf("%s" ,str)){printf("%d\n" ,Find(str));}return 0; }
總結
以上是生活随笔為你收集整理的hdu1251 hash或者字典树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu4421 2-sat(枚举二进制每
- 下一篇: hdu1247 字典树或者hash