这道题是很简单的字典树的题,很基础,直接套模板就行。
字典树的讲解见:http://blog.csdn.net/u010142538/article/details/9729601
code:
#include <iostream> #include <stdio.h> #include <cmath> #include <algorithm> #include <string> #include <cstring> #include <queue> #include <stack> #include <iomanip> #include <map> #include <climits> #include <set> #include <vector> using namespace std; typedef struct Trie { int v ; Trie *next[26] ; }; Trie root ; void createTrie(char *str) { int l = strlen(str) ; Trie *p = &root , *q ; for(int i = 0 ; i < l ; i ++) { int m = str[i] - 'a' ; if(p -> next[m] == NULL) { q = (Trie *)malloc(sizeof(root)) ; q -> v = 1 ; for(int j = 0 ; j < 26 ; j ++) q -> next[j] = NULL ; p -> next[m] = q ; p = p -> next[m] ; } else { p -> next[m] -> v ++ ; p = p -> next[m] ; } } } int findTrie(char *str) { int l = strlen(str) ; Trie *p = &root ; for(int i = 0 ; i < l ; i ++) { int m = str[i] - 'a' ; p = p -> next[m] ; if(p == NULL) return 0 ; } return p -> v ; } int main() { char tmp[15] ; //root = (Trie *)malloc(sizeof(root)) ; for(int i = 0 ; i < 26 ; i ++) root.next[i] = NULL ; while(gets(tmp) && tmp[0] != '\0') { createTrie(tmp) ; } memset(tmp , 0 , sizeof(tmp)) ; while(scanf("%s" , tmp) != EOF) { int ans = findTrie(tmp) ; printf("%d\n" , ans) ; } return 0; }