hdu 1251 统计难题(trie树入门)
生活随笔
收集整理的這篇文章主要介紹了
hdu 1251 统计难题(trie树入门)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
統(tǒng)計難題
Time Limit: 4000/2000 MS (Java/Others)????Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 24521????Accepted Submission(s): 10133
?
Input 輸入數(shù)據(jù)的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統(tǒng)計的單詞,一個空行代表單詞表的結(jié)束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.注意:本題只有一組測試數(shù)據(jù),處理到文件結(jié)束.
?
Output 對于每個提問,給出以該字符串為前綴的單詞的數(shù)量.?
Sample Input banana band bee absolute acm ba b band abc?
Sample Output 2 3 1 0?
Author Ignatius.L坑坑:用G++在杭電oj上提交會一直內(nèi)存超限~
1 #include<iostream> 2 #include<vector> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <math.h> 7 #include<algorithm> 8 #define ll long long 9 #define eps 1e-8 10 using namespace std; 11 12 struct nodes 13 { 14 int cnt; 15 struct nodes *next[26]; 16 nodes() 17 { 18 int i; 19 cnt = 0; 20 for(i = 0; i < 26; i++) 21 next[i] = NULL; 22 } 23 } root,*temp; 24 25 void inserts(char *word) 26 { 27 nodes *cur = &root; 28 while(*word ) 29 { 30 int t = *word - 'a'; 31 if(cur->next[t] == NULL) 32 { 33 temp = (nodes *)malloc(sizeof(nodes)); 34 temp->cnt = 0; 35 for(int i = 0; i < 26; i++) 36 temp->next[i] = NULL; 37 cur->next[t] = temp; 38 } 39 cur = cur->next[t]; 40 cur->cnt++; 41 word++; 42 } 43 } 44 45 void searchs(char *word) 46 { 47 nodes *cur = &root; 48 int ans = 0; 49 while(*word && cur) 50 { 51 cur = cur->next[*word - 'a']; 52 if(cur) 53 ans = cur->cnt; 54 else 55 { 56 ans = 0; 57 break; 58 } 59 word++; 60 } 61 printf("%d\n",ans); 62 } 63 64 int main(void) 65 { 66 char bank[22]; 67 char ss[50]; 68 69 while(gets(bank) && bank[0] ) 70 { 71 inserts(bank); 72 } 73 while(scanf("%s",ss) != -1) 74 { 75 searchs(ss); 76 } 77 return 0; 78 }?新增省內(nèi)存方法,STL中的map:
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <cstdlib> 5 #include <cstring> 6 #include <cmath> 7 #include <map> 8 #include <algorithm> 9 #define N 500015 10 #define INF 1000000 11 #define ll long long 12 using namespace std; 13 14 int main(void) 15 { 16 map<string,int>Q; 17 char temp[15]; 18 int l; 19 while(gets(temp) && temp[0]) 20 { 21 l = (int)strlen(temp); 22 for(int i = l; i > 0; i--) 23 { 24 temp[i] = '\0'; 25 Q[temp]++; 26 } 27 } 28 while(scanf("%s",temp) != -1) 29 { 30 printf("%d\n",Q[temp]); 31 } 32 return 0; 33 }?
轉(zhuǎn)載于:https://www.cnblogs.com/henserlinda/p/4721169.html
總結(jié)
以上是生活随笔為你收集整理的hdu 1251 统计难题(trie树入门)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机网络之网络层:12、网络层设备
- 下一篇: (计算机组成原理)第四章指令系统:本章习