一、题意
1.简述
ZJM 为了准备霍格沃兹的期末考试,决心背魔咒词典,一举拿下咒语翻译题
题库格式:[魔咒] 对应功能
背完题库后,ZJM 开始刷题,现共有 N 道题,每道题给出一个字符串,可能是 [魔咒],也可能是对应功能
ZJM 需要识别这个题目给出的是 [魔咒] 还是对应功能,并写出转换的结果,如果在魔咒词典里找不到,输出 “what?”
2.输入格式
首先列出魔咒词典中不超过100000条不同的咒语,每条格式为:
[魔咒] 对应功能
其中“魔咒”和“对应功能”分别为长度不超过20和80的字符串,字符串中保证不包含字符“[”和“]”,且“]”和后面的字符串之间有且仅有一个空格。魔咒词典最后一行以“@END@”结束,这一行不属于词典中的词条。
词典之后的一行包含正整数N(<=1000),随后是N个测试用例。每个测试用例占一行,或者给出“[魔咒]”,或者给出“对应功能”。
3.输出格式
每个测试用例的输出占一行,输出魔咒对应的功能,或者功能对应的魔咒。如果在词典中查不到,就输出“what?”
4.样例
Input
[expelliarmus] the disarming charm
[rictusempra] send a jet of silver light to hit the enemy
[tarantallegra] control the movement of one’s legs
[serpensortia] shoot a snake out of the end of one’s wand
[lumos] light the wand
[obliviate] the memory charm
[expecto patronum] send a Patronus to the dementors
[accio] the summoning charm
@END@
4
[lumos]
the summoning charm
[arha]
take me to the sky
Output
light the wand
accio
what?
what?
二、算法
主要思路
首先考虑用 m a p map map数据结构进行 s t r i n g string string到 s t r i n g string string的映射,但是发现空间超出要求了。
之后考虑用
i
n
t
int
int到
i
n
t
int
int的映射。利用字符串哈希函数,将特定字符串映射到一个特定的数
h
a
s
h
hash
hash上。
所以,我们就可以用一个
i
n
t
int
int数值来代表
s
t
r
i
n
g
string
string型的一个特定字符串。然后,利用
m
a
p
map
map将这个
h
a
s
h
hash
hash映射到其对应的魔咒或者功能的索引上去(如果该字符串是魔咒则对应的是功能,如果是功能则要对应魔咒的索引),然后构造好
m
a
p
map
map之后直接用
m
a
p
map
map查即可。空间是够的。
三、代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<sstream>
#include<cmath>
#include<map>
using namespace std;
const int seed = 7;
const int mod = 1e9+7;
const int maxn = 2e5+10;
string strg[maxn];
map<int,int> m;
int sidx;
int quick_pow(int a,int x){
int rtn = 1;
while(x){
if(x&1) rtn = rtn*a;
rtn %= mod;
a = a*a;
a %= mod;
x >>= 1;
}
return rtn;
}
int getHash(string s){
int hash = 0;
char str[82];
memset(str,0,sizeof(str));
strcpy(str,s.c_str());
for(int i=0;i<s.length();i++){
int a = str[i]; //asc码值
hash += a * quick_pow(seed,s.length()-i);
hash %= mod;
}
return hash;
}
int main(){
char c = getchar();
while(c!='@'){
char str[22];
char fun[82];
memset(str,0,sizeof(str));
memset(fun,0,sizeof(fun));
for(int i=0;;i++){ //获取咒语
char ch = getchar();
if(ch==']') break; //[]不算在字符串内
else str[i] = ch;
}
string s1 = str;
int hash1 = getHash(s1);
getchar();//去除空格
for(int i=0;;i++){ //获取功能
char ch = getchar();
if(ch=='\n') break;
else fun[i] = ch;
}
string s2 = fun;
int hash2 = getHash(s2);
m.insert(make_pair(hash1,sidx));
strg[sidx++] = s2;
m.insert(make_pair(hash2,sidx));
strg[sidx++] = s1;
c = getchar();
}
string hang;
cin>>hang;
int n;
scanf("%d",&n);
getchar(); //消除换行
for(int i=0;i<n;i++){
char str[82];
memset(str,0,sizeof(str));
char ch = getchar();
if(ch == '['){ //是咒语
for(int j=0;;j++){ //获取咒语
ch = getchar();
if(ch==']') break; //[]不算在字符串内
else str[j] = ch;
}
getchar(); //去除换行
}
else{ //是功能
str[0] = ch;
for(int j=1;;j++){ //获取功能
ch = getchar();
if(ch=='\n') break;
else str[j] = ch;
}
}
string s = str;
int hash = getHash(s);
if(m.find(hash)!=m.end()){ //找到了
int idx = m[hash];
cout<<strg[idx]<<endl;
}
else cout<<"what?"<<endl;
}
return 0;
}