题意:
ZJM 为了准备霍格沃兹的期末考试,决心背魔咒词典,一举拿下咒语翻译题
题库格式:[魔咒] 对应功能
背完题库后,ZJM 开始刷题,现共有 N 道题,每道题给出一个字符串,可能是 [魔咒],也可能是对应功能
ZJM 需要识别这个题目给出的是 [魔咒] 还是对应功能,并写出转换的结果,如果在魔咒词典里找不到,输出 “what?”
输入格式:
首先列出魔咒词典中不超过100000条不同的咒语,每条格式为:
[魔咒] 对应功能
其中“魔咒”和“对应功能”分别为长度不超过20和80的字符串,字符串中保证不包含字符“[”和“]”,且“]”和后面的字符串之间有且仅有一个空格。魔咒词典最后一行以“@END@”结束,这一行不属于词典中的词条。
词典之后的一行包含正整数N(<=1000),随后是N个测试用例。每个测试用例占一行,或者给出“[魔咒]”,或者给出“对应功能”。
输出格式:
每个测试用例的输出占一行,输出魔咒对应的功能,或者功能对应的魔咒。如果在词典中查不到,就输出“what?”
样例输入:
[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
样例输出:
light the wand
accio
what?
what?
思路:
字符串哈希
举例:
字符串:𝑎𝑒𝑑
Hash值:(1*seed3+5seed2+4seed1)%mod
seed常见取值为 7、17、131
𝑚𝑜𝑑常见取值为1𝑒9+7或采用𝑢𝑛𝑠𝑖𝑔𝑛𝑒𝑑𝑙𝑜𝑛𝑔𝑙𝑜𝑛𝑔自然溢出
解题方法:
[魔咒] 对应功能
求出魔咒哈希值为 Hash1,对应功能哈希值为 Hash2
建立两个 map :
map[Hash1] = index,s1[index] = 对应功能
map[Hash2] = index,s2[index] = 魔咒
根据查询判断是 [魔咒] 还是对应功能, 然后在对应的 map中查询即可
字符串处理:
这道题按照上面的思路做倒是不难,但是在字符串的处理上倒是改了挺多遍,在下面总结一下:
(1)cin输入字符串时,遇到空格默认结束,这里使getline(cin,s)
(2)将字符串转为char型数组类型,s.c_str()
(3)strncpy函数原型函数原型char* strncpy(char *dest,char *src,int size_tn)复制字符串src中的内容(字符,数字、汉字…)到字符串dest中,复制多少由size_tn的值决定,注意类型为char型数组,这也是上面为什么要把字符串转化为字符数组
(4)cin后回车被保存在缓冲区,需要使用getchar()接收。在本题,若cin>>N之后缺少getchar()语句,cin的第一个字符串s会是回车符,造成错误
总结:
1.掌握字符串哈希的基本方法
2.熟练对字符串的操作
代码:
#include<iostream>
#include<string>
#include<string.h>
#include<map>
using namespace std;
const int maxn=1e5+10;
string s;
char str1[maxn][85];
char str2[maxn][85];
int N,seed=7;
map<unsigned long long ,int> mp1,mp2;
unsigned long long Hash(string s){
unsigned long long ans=0,tseed=seed;
for(int i=0;i<s.size();i++){
if(s[i]!=' '&&s[i]!='['&&s[i]!=']'){
ans+=s[i]*tseed;
tseed*=tseed;
}
}
return ans;
}
int main(){
int n=0;
while(getline(cin,s)){
if(s=="@END@") break;
char ts[105];
strncpy(ts,s.c_str(),s.size());
int l=1,r=1;
for(;r<s.size()&&s[r]!=']';r++);
strncpy(str2[n],ts+1,r-1);
unsigned long long hash1=Hash(str2[n]);
mp1[hash1]=n;
l=r+2;r=s.size();
strncpy(str1[n],ts+l,r-l);
unsigned long long hash2=Hash(str1[n]);
mp2[hash2]=n;
n++;
}
cin>>N;getchar();
for(int i=0;i<N;i++){
getline(cin,s);
unsigned long long t=Hash(s);
if(s[0]=='['){
if(mp1.find(t)==mp1.end())
cout<<"what?"<<endl;
else cout<<str1[mp1[t]]<<endl;
}
else{
if(mp2.find(t)==mp2.end())
cout<<"what?"<<endl;
else cout<<str2[mp2[t]]<<endl;
}
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)