- 字典树解法(Trie树)
Accepted 1251 156MS 45400K 949 B C++ #include"iostream" #include"cstdlib" #include"cstring" #include"cstdio" using namespace std; struct tree { int cnt; tree* Next[26]; } *root; tree* init() { tree* t = (tree*) malloc(sizeof(tree)); memset(t -> Next, NULL, sizeof(t -> Next)); t -> cnt = 0; return t; } void in(char* s) { tree* now = root; for(int i = 0; s[i]; i++) { int j = s[i] - 'a'; if(! now -> Next[j]) now -> Next[j] = init(); now = now -> Next[j]; now -> cnt++; } } void out(char* s) { tree* now = root; for(int i = 0; s[i]; i++) { int j = s[i] - 'a'; if(!now -> Next[j]) { puts("0"); return; } now = now -> Next[j]; } printf("%d ", now -> cnt); } char s[12]; int main() { root = init(); while(gets(s) && s[0]) in(s); while(gets(s)) out(s); return 0; }
- 二叉搜索树解法(BST)
Accepted 1251 358MS 18864K 1443B G++ #include "bits/stdc++.h" using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; struct BST { char key[11]; int value; BST* lson; BST* rson; }*root; char s[11]; BST* init() { BST* point = (BST*)malloc(sizeof(BST)); strcpy(point->key, s); point->value = 1; point->lson = point->rson = NULL; return point; } void insert() { BST* father = NULL; BST* now = root; int cmp; while (now != NULL) { cmp = strcmp(now->key, s); if (cmp == 0) { now->value++; return; } else if (cmp == -1) { father = now; now = now->rson; } else { father = now; now = now->lson; } } if (father == NULL) { root = init(); } else if (cmp == -1) { father->rson = init(); } else { father->lson = init(); } } int query() { BST* now = root; while (now != NULL) { int cmp = strcmp(now->key, s); if (cmp == 0) { return now->value; } else if (cmp == -1) { now = now->rson; } else { now = now->lson; } } return 0; } int main() { while (gets(s) && s[0]) { int len = strlen(s); while (len != 0) { s[len--] = '