HDU 1075 字典树基础题

本文介绍了一种使用字典树(Trie)来高效处理字符串映射问题的方法。通过构建字典树,可以快速地插入和查询字符串,特别适用于处理大量字符串映射关系的场景。文章提供了一个具体的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:字符串中单词的映射

可用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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值