题意:给出一个字典,然后给出一系列相对应的单词,进行查询,没有输出"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;
}//