题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1075
题目大意:给出一些火星文的英文翻译,然后翻译句子。
分析:可以用字典树,用map更方便一点,标点符号和句子中的单词分离有点麻烦。
字典树代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<string>
#include<sstream>
#include<map>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+50//不要开小了;
typedef long long ll;
string S[N];
string s,s1;
struct node
{
struct node *next[26];
int flag;
node()
{
for(int i=0;i<26;i++)
{
flag=-1;
next[i]=NULL;
}
}
};
node *root=new node();
void creat(string s,int t)
{
node *p=root;
int len=s.length();
for(int i=0;i<len;i++)
{
int k=s[i]-'a';
if(!p->next[k])
{
p->next[k]=new node();
}
p=p->next[k];
}
p->flag=t;
}
int find(string s)
{
int len=s.length();
node *p=root;
for(int i=0;i<len;i++)
{
int k=s[i]-'a';
if(!p->next[k])
return -1;
p=p->next[k];
}
return p->flag;
}
int main(){
ll t=0;
cin>>s;
while(getline(cin,s))
{
if(s=="END")
break;
string a="",b="";
int f=1;
for(int i=0;i<s.size();i++)
{
if(s[i]==' ')
{
f=0;
continue;
}
if(f)
{
a+=s[i];
}
else
{
b+=s[i];
}
}
S[t]=a;
creat(b,t);
t++;
}
cin>>s;
getchar();
while(getline(cin,s))
{
if(s[0]=='E')
break;
int len=s.length();
s+='\n';//不能省
s+='\0';
string p="";
int f=0;
for(int i=0;i<=len;i++)
{
while(s[i]>='a'&&s[i]<='z')
{
p+=s[i];
f=1;
i++;
}
if(f)
{
if(find(p)==-1)
printf("%s",p.c_str());
else
printf("%s",S[find(p)].c_str());
f=0;
i--;
continue;
}
p="";
printf("%c",s[i]);
}
}
return 0;
}
map(差不多):
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<string>
#include<sstream>
#include<map>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
string s;
int main(){
cin>>s;
map<string,string>mp;
while(getline(cin,s)){
if(s=="END")break;
string a="",b="";
int f=1;
for(int i=0;i<s.size();i++){
if(s[i]==' '){
f=0;
continue;
}
if(f){
a+= s[i];
}else{
b+=s[i];
}
}
mp[b]=a;
}
cin>>s;
getchar();
while(getline(cin,s)){
if(s=="END")break;
int len = s.length();
s+='\n';//不能省
s+='\0';
string p="";
int f=0;
for(int i=0;i<=len;i++){
while(s[i]>='a'&&s[i]<='z'){
p+=s[i];
f=1;
i++;
}
if(f){
if(mp[p]=="")printf("%s",p.c_str());
else printf("%s",mp[p].c_str());
f=0;
i--;
continue;
}
p="";
printf("%c",s[i]);
}
}
return 0;
}