《算法竞赛-训练指南》-第三章-Trie
2013-09-09 17:25
267 查看
#include <stdio.h> #include <string.h> #include <iostream> #include <string> using namespace std; const int MAXNODE = 1000000 + 11; const int SEGMA_SIZE = 26; struct Trie { int ch[MAXNODE][SEGMA_SIZE]; int val[MAXNODE]; int size; Trie() { size = 1; memset(ch[0], 0, sizeof(ch[0])); } void clear() { size = 1; memset(ch[0], 0, sizeof(ch[0])); } int idx(char c) // 求出字符所对应的id { return c - 'a'; } void insert(char *s, int v) { int n = strlen(s); int u = 0; for (int i = 0; i < n; i++) { int id = idx(s[i]); if (!ch[u][id]) { memset(ch[size], 0, sizeof(ch[size])); val[size] = 0; ch[u][id] = size++; } u = ch[u][id]; } val[u] = v; } int search(char *s) { int n = strlen(s); int u = 0; for (int i = 0; i < n; i++) { int id = idx(s[i]); if (!ch[u][id]) { return 0; } u = ch[u][id]; } if (val[u] == 1) { return 1; } } }trie; int main() { char str[111]; int N, M; while (scanf("%d%d", &N, &M) != EOF) { trie.clear(); for (int i = 0; i < N; i++) { scanf("%s", str); trie.insert(str, 1); } for (int i = 0; i < M ; i++) { scanf("%s", str); int ans = trie.search(str); if (ans == 1) { printf("The string exists\n"); } else { printf("The string doesn`t exist\n"); } } } system("pause"); return 0; }
相关文章推荐
- 《算法竞赛-训练指南》第三章-3.6_LA 3027(并查集)
- 《算法竞赛-训练指南》第三章-3.1_UVa 11995(STL数据结构运用)
- 《算法竞赛-训练指南》第三章-2.2_UVa 11991
- 《算法竞赛-训练指南》第三章-3.7_LA 3429(树状数组)
- 《算法竞赛-训练指南》第三章-RMQ
- 《算法竞赛-训练指南》第三章-3.8_UVa 11235
- 《算法竞赛-训练指南》第一章-1.19_UVa 11549
- 《算法竞赛-训练指南》第二章-2.3_UVa 11806
- 《算法竞赛-训练指南》第二章-数论_高斯消元
- 《算法竞赛-训练指南》-第一章-1.10_UVa 11384
- 《算法竞赛-训练指南》第二章-2.1_UVa 11538
- 《算法竞赛-训练指南》第一章-1.20_LA 3905
- 《算法竞赛-训练指南》第一章-1.28_UVa 10891
- 《算法竞赛-训练指南》第二章-数论常用算法总结
- 《算法竞赛-训练指南》第二章-2.9_UVa 11426
- 《算法竞赛-训练指南》-第二章-2.16_UVa 11427
- 《算法竞赛-训练指南》第一章-1.4_LA 3708
- 算法竞赛入门训练指南 exe_1
- 《算法竞赛-训练指南》第二章-HDU_2018
- 《算法竞赛-训练指南》第一章-1.9——UVa11210