hdu 1075 What Are You Talking Abou

来源:互联网 发布:移动卡无法访问网络 编辑:程序博客网 时间:2024/06/02 18:47

       hdu 1075 What Are You Talking About

       字典树啦, 指针处理起来要小心一点哦, 而且字典树的代码又有点长, 有模板直接用就很爽啦.


#include <stdio.h>#include <malloc.h>#include <string.h>#define SIZE 26#define LENGTH 15struct TrieNode {    char* en;    TrieNode* next[SIZE];};void init(TrieNode* root) {    root = NULL;}TrieNode* createTrieNode() {    TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));    int i;    node->en = NULL;    for (i = 0; i < 26; i++) {        node->next[i] = NULL;    }    return node;}void insert(TrieNode** root, char* str, char* en) {    int i, index;    TrieNode* p;    if (!(p = *root)) {        p = *root = createTrieNode();    }    i = 0;    while (str[i]) {        index = str[i] - 'a';        if (!p->next[index]) {            p->next[index] = createTrieNode();        }        p = p->next[index];        i++;    }    p->en = (char*)malloc(strlen(en));    strcpy(p->en, en);}char* search(TrieNode* root, char* str) {    int i, index;    TrieNode* p;    if (!(p = root)) {        return NULL;    }    i = 0;    while (str[i]) {        index = str[i] - 'a';        if (!p->next[index]) {            return NULL;        }        p = p->next[index];        i++;    }    return p->en;}void del(TrieNode* root) {    int i;    for (i = 0; i < SIZE; i++) {        if (root->next[i]) {            del(root->next[i]);        }    }    // if (root->en != NULL) free(root->en);    free(root);}char* toTranslate(TrieNode* dirc, char* s) {    int i, k, j, l;    int len;    char ens[10000];    char word[200];    char* en;    len = strlen(s);    k = j = 0;    memset(ens, '\0', sizeof(ens));    memset(word, '\0', sizeof(word));    for (i = 0; i <= len; i++) {        if (s[i] >= 'a' && s[i] <= 'z') {            word[k++] = s[i];        } else {            if (k > 0) {                word[k] = '\0';                en = search(dirc, word);                if (!en) {                    for (l = 0; word[l] != '\0'; l++) {                        ens[j++] = word[l];                    }                } else {                    for (l = 0; en[l] != '\0'; l++) {                        ens[j++] = en[l];                    }                }                ens[j++] = s[i];                k = 0;                // memset(word, '\0', sizeof(word));            } else {                ens[j++] = s[i];            }        }    }    // ens[j] = '\0';        strcpy(s, ens);    return s;}int main() {    int k;    char en[200], mars[200];    // char s[10][10000];    char s[400000];    TrieNode* root = NULL;    init(root);    scanf("%s", en);    while (true) {        scanf("%s", en);        if (!strcmp(en, "END")) break ;        scanf("%s", mars);        insert(&root, mars, en);    }    k = 0;    scanf("%s", en);    getchar();    while (true) {        gets(s);        if (!strcmp(s, "END")) break ;        // k++;        printf("%s\n", toTranslate(root, s));    }    return 0;}


原创粉丝点击