本文主要是介绍Week15 A ZJM 与霍格沃兹,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
ZJM 与霍格沃兹
ZJM 为了准备霍格沃兹的期末考试,决心背魔咒词典,一举拿下咒语翻译题
题库格式:[魔咒] 对应功能
背完题库后,ZJM 开始刷题,现共有 N 道题,每道题给出一个字符串,可能是 [魔咒],也可能是对应功能
ZJM 需要识别这个题目给出的是 [魔咒] 还是对应功能,并写出转换的结果,如果在魔咒词典里找不到,输出 “what?”
Input
首先列出魔咒词典中不超过100000条不同的咒语,每条格式为:
[魔咒] 对应功能
其中“魔咒”和“对应功能”分别为长度不超过20和80的字符串,字符串中保证不包含字符“[”和“]”,且“]”和后面的字符串之间有且仅有一个空格。魔咒词典最后一行以“@END@”结束,这一行不属于词典中的词条。
词典之后的一行包含正整数N(<=1000),随后是N个测试用例。每个测试用例占一行,或者给出“[魔咒]”,或者给出“对应功能”。
Output
每个测试用例的输出占一行,输出魔咒对应的功能,或者功能对应的魔咒。如果在词典中查不到,就输出“what?”
Sample 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
Sample Output
light the wand
accio
what?
what?
问题分析
题意非常好理解,利用map结构将功能和咒语对应起来即可。一开始是直接存储字符串map<string,string>,但是会MLE。
改成map<long long ,string>,将字符串转换为hash值存储。求hash值:
建立两个map数组存储字典,map1:key为咒语,value为功能;map2:key为功能,value为咒语。
输入要判断的字符串,先判断是咒语还是功能,在计算hash值,如果是咒语,在map1中寻找其功能;如果是功能,在map2中寻找其咒语。
代码实现
#include<iostream>
#include<map>
#include<string>
#include<math.h>
using namespace std;map<long long, string> book1,book2;
map<long long, string>::iterator it;
long long mod = 100000007 ;
int n;
string s,str;int main()
{getline(cin,s);long long hash1,hash2;while(s!="@END@"){hash1=hash2=0;int in=s.find(']');string temp = s.substr(1,in-1);str = s.substr(in+2);long long seed=7;for(int i=0; i<temp.size(); i++){if(temp[i]!=' '){hash1+=((temp[i])*seed)%mod;seed = seed*7%mod;}}seed=7; for(int i=0; i<str.size(); i++){if(str[i]!=' '){hash2+=((str[i])*seed)%mod; seed=seed*7%mod;}}// cout<<"hash1:"<<hash1<<endl;// cout<<"hash2:"<<hash2<<endl;book1.insert(pair<long long,string>(hash1,str));book2.insert(pair<long long,string>(hash2,temp));// it=book1.find(hash1);// cout<<it->second<<endl;getline(cin,s);}cin>>n;getchar();for(int i=0; i<n; i++){string temp;getline(cin,temp);bool d=true;long long hash=0;if(temp[0]=='['){int len=temp.size();string ss=temp.substr(1,len-2);long long seed=7;for(int i=0; i<ss.size(); i++){if(ss[i]!=' '){hash+=((ss[i])*seed)%mod;seed=seed*7%mod;}}// cout<<hash<<endl;it=book1.find(hash);if(it != book1.end()){cout<<it->second<<endl;}elsecout<<"what?"<<endl;}else{long long seed=7;for(int i=0; i<temp.size(); i++){if(temp[i]!=' '){hash+=((temp[i])*seed)%mod;seed = seed*7%mod;} }// cout<<hash<<endl;it=book2.find(hash);if(it != book2.end()){cout<<it->second<<endl;}elsecout<<"what?"<<endl;}}
}
这篇关于Week15 A ZJM 与霍格沃兹的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!