书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

链表的典型应用——字典树

题目:http://acm.swust.edu.cn/oj/problem/842/

这个题目是有一点复杂的,因为在存储内容的时候又再次用了链表。

可以说它是链表题目的相当典型的例子了。

 

还是直接上代码吧。

复制代码
View Code
#include "iostream"
#include "cstring"
#include "string"
#include "cstdio"
#include "algorithm"
#include "malloc.h"
using namespace std;
typedef struct word{
    char Chn[4];
    struct word *next;
}word;
typedef struct node{
    int mark;
    word *str;
    struct node *next[26];
}node;
node *head;
void InitHead(){
    head = (node *)malloc(sizeof(node));
    head->mark = 0;
    head->str = NULL;
    memset(head->next, NULL, sizeof(head->next));
}
void Build(char *Eng, char *Chn){
    node *p = head;
    word *w;
    int i, k, Len = strlen(Eng);
    for(i=0; i<Len; i++){
        k = Eng[i]-'a';
        if(p->next[k]==NULL){
            p->next[k] = (node*)malloc(sizeof(node));
            p->next[k]->mark = 0;
            p->next[k]->str = NULL;
            memset(p->next[k]->next, NULL, sizeof(p->next[k]->next));
        }
        p = p->next[k];
        if(i==Len-1){
            p->mark = 1;
            if(p->str==NULL){
                p->str=(word*)malloc(sizeof(word));
                strcpy(p->str->Chn, Chn);
                p->str->next = NULL;
            }else{
                w = p->str;
                while(w->next!=NULL) w=w->next;
                w=w->next=(word*)malloc(sizeof(word));
                strcpy(w->Chn, Chn);
                w->next = NULL;
            }
        }
    }
}
char *Find(char *Eng, int n){
    int i, j, k, Len = strlen(Eng);
    node *p = head;
    word *w;
    for(i=0; i<Len; i++){
        k = Eng[i]-'a';
        p = p->next[k];
        if(p==NULL) return "NO";
        
        if(i==Len-1){
            if(p->mark==0) return "NO";
            w = p->str;
            for(j=1; j<n && w->next!=NULL; j++) w = w->next;
            return w->Chn;
        }
    }
}
int main(){
    char Eng[100], Chn[4];
    int n;
    InitHead();
    while(cin>>Eng){
        if(strcmp(Eng, "end")==0) break;
        cin>>Chn;
        Build(Eng, Chn);
    }
    while(cin>>Eng){
        if(strcmp(Eng, "end")==0) break;
        cin>>n;
        cout<<Find(Eng, n)<<endl;
    }
    return 0;
}
复制代码

但是这里有一个十分蛋疼的现象:

就是你将上面代码中的所有char *改成string之后,

竟然会出现奇怪的现象,也就是什么什么冲突。

无语呀…………………………………………………………。

posted on   More study needed.  阅读(261)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
< 2012年4月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 1 2 3 4 5
6 7 8 9 10 11 12

导航

统计

书山有径勤为路>>>>>>>>

<<<<<<<<学海无涯苦作舟!

点击右上角即可分享
微信分享提示