hdu -1251 统计难题(字典树水题)
http://acm.hdu.edu.cn/showproblem.php?pid=1251
建树之后 查询即可.
G++提交 ME不知道为什么,c++就对了。
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <vector> 5 #include <cstring> 6 #include <string> 7 #include <algorithm> 8 #include <string> 9 #include <set> 10 #include <functional> 11 #include <numeric> 12 #include <sstream> 13 #include <stack> 14 #include <map> 15 #include <queue> 16 #include <deque> 17 //#pragma comment(linker, "/STACK:102400000,102400000") 18 #define CL(arr, val) memset(arr, val, sizeof(arr)) 19 20 #define ll long long 21 #define INF 0x7f7f7f7f 22 #define lc l,m,rt<<1 23 #define rc m + 1,r,rt<<1|1 24 #define pi acos(-1.0) 25 26 #define L(x) (x) << 1 27 #define R(x) (x) << 1 | 1 28 #define MID(l, r) (l + r) >> 1 29 #define Min(x, y) (x) < (y) ? (x) : (y) 30 #define Max(x, y) (x) < (y) ? (y) : (x) 31 #define E(x) (1 << (x)) 32 #define iabs(x) (x) < 0 ? -(x) : (x) 33 #define OUT(x) printf("%I64d\n", x) 34 #define lowbit(x) (x)&(-x) 35 #define Read() freopen("a.txt", "r", stdin) 36 #define Write() freopen("b.txt", "w", stdout); 37 #define maxn 310 38 #define maxv 50010 39 #define mod 1000000000 40 using namespace std; 41 42 typedef struct node 43 { 44 int count; 45 struct node *next[26]; 46 }*tree; 47 48 void insert(tree p,char *s) 49 { 50 tree h=p; 51 int l=strlen(s); 52 for(int i=0;i<l;i++) 53 { 54 int index=s[i]-'a'; 55 if(h->next[index]!=NULL) 56 { 57 h=h->next[index]; 58 h->count++; 59 } 60 else 61 { 62 tree tem=(tree)calloc(1,sizeof(node)); 63 tem->count=1; 64 h->next[index]=tem; 65 h=tem; 66 } 67 } 68 } 69 70 int find(tree p,char *s) 71 { 72 tree h=p; 73 int l=strlen(s); 74 for(int i=0;i<l;i++) 75 { 76 int index=s[i]-'a'; 77 if(h->next[index]==NULL) return 0; 78 h=h->next[index]; 79 } 80 return h->count; 81 } 82 int main() 83 { 84 //Read(); 85 char s[15]; 86 tree head=(tree)calloc(1,sizeof(node)); 87 while(gets(s)&&s[0]) 88 { 89 insert(head,s); 90 //printf("%s\n",s); 91 } 92 //printf("1\n"); 93 while(~scanf("%s",s)) 94 { 95 printf("%d\n",find(head,s)); 96 } 97 free(head); 98 return 0; 99 }