POJ 2503 字典树

 

题目链接:http://poj.org/problem?id=2503

题意:给定一个词典,输入格式为[string1' 'string2]  意思是string2的值为string1。 然后给定一波字符串问你该字符串在字典的值是多少? 

思路:字典树模板题。  叶子结点存放的是对应词典中的值。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<time.h>
#include<sstream>
#include<map>
using namespace std;
const int MAXN=300000+5;
const int MAXL=10+5;
char str[MAXL],val[MAXL],ch[MAXL];
struct trie{
    char val[MAXL];
    int child[26];
    trie(){
        memset(child,0,sizeof(child));
    }
}Trie[MAXN];
int TrieN;
void Insert(char *str,char *Val){
    int x=0,len=strlen(str);
    for(int i=0;i<len;i++){
        int d=str[i]-'a';
        if(Trie[x].child[d]==0){
            Trie[++TrieN]=trie();
            Trie[x].child[d]=TrieN;
        }
        x=Trie[x].child[d];
    }
     strcpy(Trie[x].val,Val);
}
void Search(char *str,char *ans){
    int x=0,len=strlen(str);
    for(int i=0;i<len;i++){
        int d=str[i]-'a';
        if(Trie[x].child[d]==0){
            strcpy(ans,"eh");
            return;
        }
        x=Trie[x].child[d];
    }
    strcpy(ans,Trie[x].val);
}
int main(){
#ifdef kirito
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    int start=clock(); TrieN=0;
    while(gets(ch)&&ch[0]){
        int lenc=strlen(ch),lens=0,lenv=0; 
        bool flag=false;
        for(int i=0;i<lenc;i++){
            if(ch[i]==' '){flag=true;continue;}
            if(!flag){
                val[lenv++]=ch[i];
            }
            else{
                str[lens++]=ch[i];
            }
        }
        val[lenv]='\0'; str[lens]='\0';
        Insert(str,val);
    }
    while (~scanf("%s",str)){
        if(!str[0]){break;}
        Search(str,val);
        printf("%s\n",val);
    }
#ifdef LOCAL_TIME
    cout << "[Finished in " << clock() - start << " ms]" << endl;
#endif
    return 0;
}

 

转载于:https://www.cnblogs.com/kirito520/p/5665948.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值