您的位置:首页 > 理论基础 > 数据结构算法

HDU 1277 - 全文检索

2015-07-28 20:04 519 查看
用字典树做的,要把输入的M行数据存到一个数组中即可。。

由于题目给出任何两个关键字的前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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字典树 数据结构 HDU