Babelfish UVA - 10282(map/字典树)

传送门

题意:给出一个字典,然后给出一系列相对应的单词,进行查询,没有输出"eh",有的话输出相应的单词。

题解:可以使用map或者字典树

附上代码:(map)

#include<bits/stdc++.h>

using namespace std;

map<string,string>mp;

int main()
{
    string line,key,val;
    while(getline(cin,line)){
        if(line.length()==0){
            break;
        }
        stringstream sin(line);
        sin>>key>>val;
        mp[val]=key;
    }
    while(getline(cin,line)){
        int i=mp.count(line);
        if(i){
            cout<<mp[line]<<endl;
        }else{
            cout<<"eh"<<endl;
        }
    }
    return 0;
}

附上代码:(字典树)

#include<bits/stdc++.h>

using namespace std;

const int maxn=1e5+50;
const int maxnode=1e6+50;
const int sigma_size=26;

struct Trie{
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int sz;
    void clear(){
        sz=1;
        memset(ch[0],0,sizeof(ch[0]));
    }
    int idx(char c){
        return c-'a';
    }
    void insert(string s,int v){
        int u=0,n=s.size();
        for(int i=0;i<n;i++){
            int c=idx(s[i]);
            if(!ch[u][c]){
                memset(ch[sz],0,sizeof(ch[sz]));
                val[sz]=0;
                ch[u][c]=sz++;
            }
            u=ch[u][c];
        }
        val[u]=v;
    }
    void find_prefixes(string s,int len,int &ans){
        int u=0;
        for(int i=0;i<len;i++){
            if(s[i]=='\0'){
                break;
            }
            int c=idx(s[i]);
            if(!ch[u][c]){
                return ;
            }
            u=ch[u][c];
        }
        ans=val[u];
        return ;
    }
};
Trie trie;

string line,key,val;
string keys[maxn];
int cnt;

int main()
{
    cnt++;
    trie.clear();
    while(getline(cin,line)){
        if(line.length()==0){
            break;
        }
        stringstream sin(line);
        sin>>key>>val;
        trie.insert(val,cnt);
        keys[cnt++]=key;
    }
    while(getline(cin,line)){
        int ans=0;
        trie.find_prefixes(line,line.size(),ans);
        if(ans){
            cout<<keys[ans]<<endl;
        }else{
            cout<<"eh"<<endl;
        }
    }
    return 0;
}//

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值