HDU 1277 - 全文检索
2015-07-28 20:04
519 查看
用字典树做的,要把输入的M行数据存到一个数组中即可。。
由于题目给出任何两个关键字的前4个数字是不同的,所以不会超时。
由于题目给出任何两个关键字的前4个数字是不同的,所以不会超时。
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <algorithm> #include <ctype.h> #include <iostream> #include <set> #include <map> #include <queue> #include <stack> #include <assert.h> #include <time.h> #include <sstream> typedef long long LL; const int INF = 500000001; const double EPS = 1e-9; const double PI = acos(-1.0); using namespace std; char ch[600500]; char k[10005][65]; int cnt; bool flag; struct Trie { struct Trie *next[10]; int where; }; Trie *H; Trie *init() { Trie *tmp = new Trie; for(int i = 0; i < 10; i++) { tmp->next[i] = NULL; } tmp->where = -1; return tmp; } void insert(char *s, int id, Trie *tmp) { int len = strlen(s); for(int i = 0; i < len; i++) { int k = s[i] - '0'; if(tmp->next[k] == NULL) { tmp->next[k] = init(); } tmp = tmp->next[k]; } tmp->where = id; } void query(char *s, Trie *tmp) { int len = strlen(s); for(int i = 0; i < len; i++) { int k = s[i] - '0'; if(tmp->next[k] == NULL) { return ; } tmp = tmp->next[k]; if(tmp->where != -1) { printf(" [Key No. %d]", tmp->where); flag = false; return ; } } } void del(Trie *tmp) { for(int i = 0; i < 10; i++) { if(tmp->next[i]) { del(tmp->next[i]); } } free(tmp); } int main() { #ifdef _Te3st freopen("test0.in", "r", stdin); freopen("test0.out", "w", stdout); srand(time(NULL)); #endif int M, N; while(~scanf("%d %d", &M, &N)) { flag = true; H = init(); cnt = 0; getchar(); for(int i = 0; i < M; i++) { char c; while((c = getchar()) && c != '\n') { ch[cnt++] = c; } } char cc[65]; for(int i = 1; i <= N; i++) { scanf("%*s%*s%*s%s", cc); insert(cc, i, H); } printf("Found key:"); for(int i = 0; i < cnt; i++) { query(ch + i, H); } if(flag) { printf("No key can be found !"); } puts(""); } return 0; }
相关文章推荐
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- C#数据结构揭秘一
- 数据结构之Treap详解
- JavaScript数据结构和算法之图和图算法
- Java数据结构及算法实例:冒泡排序 Bubble Sort
- Java数据结构及算法实例:插入排序 Insertion Sort
- Java数据结构及算法实例:考拉兹猜想 Collatz Conjecture
- java数据结构之java实现栈
- java数据结构之实现双向链表的示例
- Java数据结构及算法实例:选择排序 Selection Sort
- Java数据结构及算法实例:朴素字符匹配 Brute Force
- Java数据结构及算法实例:汉诺塔问题 Hanoi
- Java数据结构及算法实例:快速计算二进制数中1的个数(Fast Bit Counting)
- java数据结构和算法学习之汉诺塔示例
- Java数据结构及算法实例:三角数字
- Java数据结构之简单链表的定义与实现方法示例
- 数据结构之AVL树详解
- qqwry.dat的数据结构图文解释第1/2页
- JavaScript中数据结构与算法(五):经典KMP算法