week15-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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sample output
light the wand
accio
what?

what?

解题思路:

数据处理:

读入操作中 一次读取一行  有C  scanf("%[^ ]",str);   or     getline(cin,str)   getchar();

然后分开为魔咒和功能即可。

算法:

根据字符串得到相应的hash值  。

再用两个 map<int,string>   存储魔咒和功能,通过hash互相映射。

代码:

 1 #include<iostream>
 2 #include<string>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<map>
 6 #include<vector>
 7 using namespace std;
 8 typedef long long ll;
 9 const ll seed = 7;
10 const ll mod = 1e9+7; 
11 int n;
12 vector<string> vs;
13 ll Hash(string s){
14     ll hash = 0;
15     ll len = s.length();
16     for(int i=0;i<len;i++){
17         ll t =  pow(seed,len-i);
18         hash += (t*(ll(s[i]-'0')))%mod;        
19     }     //
20     return hash%mod;
21 }
22 int main(){
23     map<int,string> m1,m2;
24     string str,s1,s2;
25     while(1){
26         getline(cin,str);
27         if(str=="@END@")
28             break;
29         int idx=0;
30         while(str[idx]!=']'){
31             idx++;
32         }
33         s1 = str.substr(1,idx-1);
34         s2 = str.substr(idx+2,str.length()-1);
35         m1[Hash(s1)] = s2;
36         m2[Hash(s2)] = s1;
37     //    cout<<s1<<" "<<s2<<endl;
38     }        
39     cin>>n;
40     getchar();
41     while(n--){
42         getline(cin,str);
43         if(str[0]=='[')
44         str = str.substr(1,str.size()-2);        
45         //cout<<str<<endl;
46         ll it = Hash(str);
47         if(m1.find(it)!=m1.end())
48             cout<<m1.find(it)->second<<endl;
49             //cout<<m1[it]<<endl;
50         else if(m2.find(it)!=m2.end())
51             cout<<m2.find(it)->second<<endl;
52         else
53             cout<<"what?"<<endl;
54     }
55 
56     return 0;    
57 }
原文地址:https://www.cnblogs.com/liuzhuan-xingyun/p/13049097.html