HDU 1075-What Are You Talking About(Trie)

题意:

给你一个字典 一个英文单词对应一个火星单词 给你一段火星文翻译成英文 字典上的没有的不翻译

分析:

没有给数据规模 字典树用链表

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <complex>
#include <cassert>
#include <utility>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int,int> PII;
typedef long long ll;
#define lson l,m,rt<<1
#define pi acos(-1.0)
#define rson m+1,r,rt<<11
#define All 1,N,1
#define read freopen("in.txt", "r", stdin)
const ll  INFll = 0x3f3f3f3f3f3f3f3fLL;
const int INF= 0x7ffffff;
const int maxn = 1e5+100;
const int mod =  1000000007;
struct trie{
    string tran;
    trie *next[26];
};
trie *root;
void init(){
    root=new trie;
    root->tran[0]='*';
    for(int i=0;i<26;++i)
        root->next[i]=NULL;
}
void build(string eng,string mar){
    int l=mar.length();
    trie *p=root;
    for(int i=0;i<l;++i){
        int tmp=mar[i]-'a';
        if(p->next[tmp]==NULL){
            p->next[tmp]=new trie;
            p=p->next[tmp];
            p->tran[0]='*';
            for(int j=0;j<26;++j)
                p->next[j]=NULL;
        }
        else{
            p=p->next[tmp];
        }
    }
    p->tran=eng;//存对应的英文单词
}
void dele(trie *root){
    for(int i=0;i<26;++i){
        if(root->next[i]!=NULL)
            dele(root->next[i]);
    }
    delete(root);
}
string query(string mar){
    int l=mar.length();
    trie *p=root;
    for(int i=0;i<l;++i){
        int tmp=mar[i]-'a';
        if(p->next[tmp]==NULL)return mar;//没查到
        p=p->next[tmp];
    }
    if(p->tran[0]=='*')return mar;
    return p->tran;
}
int main()
{
    init();
    string  s1,s2;
    while(cin>>s1){
        if(s1=="START")continue;
        if(s1=="END")break;
        cin>>s2;
        build(s1,s2);
    }
    getchar();
    while(getline(cin,s1)){
        if(s1=="START")continue;
        if(s1=="END")break;
        string str1="",str2="";
        for(int i=0;i<s1.length();++i){
            if(s1[i]>='a'&&s1[i]<='z'){
                str1+=s1[i];
            }
            else{
                str2+=query(str1);
                str1="";
                str2+=s1[i];
            }
        }
        cout<<str2<<endl;
    }
   // dele(root);
return 0;
}

 

posted on 2015-08-09 16:57  积跬步、至千里  阅读(137)  评论(0编辑  收藏  举报

导航