您的位置:首页 > 其它

HDU 1075 字典树基础题

2013-07-22 17:37 337 查看
题意:字符串中单词的映射

可用map,不过写字典树当然快多了

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一类的
#define MAX 100005
#define INF 0x7FFFFFFF
#define REP(i,s,t) for(int i=(s);i<=(t);++i)
#define ll long long
#define mem(a,b) memset(a,b,sizeof(a))
#define mp(a,b) make_pair(a,b)
#define L(x) x<<1
#define R(x) x<<1|1
# define eps 1e-5
//#pragma comment(linker, "/STACK:36777216") ///传说中的外挂
using namespace std;
char str[4000];
struct trie {
int flag;
char word[20];
trie *next[33];
trie() {
flag = 0;
memset(word,0,sizeof(word));
memset(next,0,sizeof(next));
}
}*root = new trie();

void insert(char *key, char *word) {
trie * tmp = root ;
while(*key) {
if(tmp->next[*key - 'a'] == NULL) {
tmp->next[*key - 'a'] = new trie();
}
tmp = tmp->next[*key - 'a'];
key++;
}
tmp->flag = 1;
strcpy(tmp->word,word);
}

int query(char *key) {
trie *tmp = root;
while(*key) {
if(tmp->next[*key - 'a'] == NULL) {
return 0;
}
tmp = tmp->next[*key - 'a'];
key++;
}
if(tmp->flag == 0) {
return 0;
}
printf("%s",tmp->word);
return 1;
}

int main() {
char str1[30],str2[30];
while(scanf("%s",str1)) {
if(str1[0] == 'S') continue;
if(str1[0] == 'E') break;
scanf("%s",str2);
insert(str2,str1);
}
getchar();
while(gets(str)) {
if(str[0] == 'S') continue;
if(str[0] == 'E') break;
int len = strlen(str);
char tmp[40];
int st = 0;
for(int i=0; i<len; i++) {
if(str[i] < 'a' || str[i] > 'z') {
tmp[st] = '\0';
if(strlen(tmp) != 0) {
if(query(tmp) == 0) printf("%s",tmp);
}
printf("%c",str[i]);
memset(tmp,0,sizeof(tmp));
st = 0;
} else {
tmp[st] = str[i];
st++;
}
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: