zoukankan      html  css  js  c++  java
  • 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]=''; str[lens]='';
            Insert(str,val);
        }
        while (~scanf("%s",str)){
            if(!str[0]){break;}
            Search(str,val);
            printf("%s
    ",val);
        }
    #ifdef LOCAL_TIME
        cout << "[Finished in " << clock() - start << " ms]" << endl;
    #endif
        return 0;
    }
  • 相关阅读:
    Java的格式化输出
    常用排序算法的Python实现
    零基础自学用Python 3开发网络爬虫(一)
    Python常见数据结构整理
    百度天气预报API的使用(java版本)
    大总结
    CCS学习(三)
    CSS学习(页外引用还不懂)
    CSS自定义动画
    ssm日期格式转换
  • 原文地址:https://www.cnblogs.com/kirito520/p/5665948.html
Copyright © 2011-2022 走看看