A - ZJM 与霍格沃兹(必做)
描述:
输入:
输出:
样例:
输入:
[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值保存在map中,最后在map中搜索。
计算hash值可以直接按照公式一个一个算,为了节约时间对于seed的乘法可以采用乘法快速幂计算。还可以采用提公因式计算,这样乘的次数取决于最高次。
提公因子对应代码为:
long long Hash(string x)
{
long ans=0;
for(int i=0;i<x.length();i++){
//辗转相乘;
ans = (ans + (long long)(x[i]*seed))%inf;
ans = ans*seed%inf;
}
return ans;
}
t1 = s.substr(0, s.find("] “)+1);
t2 = s.substr(s.find(”] “)+2, s.length() - s.find(”] ") - 1);
substr方法有效的提取想要的指定部分,然后将他们push进vector,对应的map记录,这里连续存放,方便后续提取。
对于查询的字符串直接
getline(cin, s);if(mp.find(Hash(s)) != mp.end() )判断是否存在在map中,若存在再进一步判断类型。
代码:
/*
字符串hash;
*/
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int inf = 1e9;
const int seed=7;//hash种子;
map<long long,int> mp;
string s,t1,t2;
vector<string> a;
char c;
int cnt,N;
//返回hash值;
long long Hash(string x)
{
long ans=0;
for(int i=0;i<x.length();i++){
//辗转相乘;
ans = (ans + (long long)(x[i]*seed))%inf;
ans = ans*seed%inf;
}
return ans;
}
void loadSpell(){
//加载字符串咒语;
while(1){
getline(cin,s);
if(s=="@END@")break;
//分别提取指定子串;]后有空格;
t1 = s.substr(0, s.find("] ")+1);
//cout<<t1<<endl;
t2 = s.substr(s.find("] ")+2, s.length() - s.find("] ") - 1);
//cout<<t2<<endl;
a.push_back(t1);
a.push_back(t2);
mp[Hash(t1)]=cnt++;
mp[Hash(t2)]=cnt++;
}
}
int main()
{
loadSpell();
cin>>N;
getchar();
while (N--)
{
getline(cin, s);
if(mp.find(Hash(s)) != mp.end() )
{
//找到;
if(s[0]=='['){
string t=a[mp[Hash(s)]+1];
cout<<t<<endl;
}
else{
string t=a[mp[Hash(s)]-1];
cout<<t.substr(1,t.length()-2)<<endl;
}
}
else
{
//未找到;
cout<<"what?"<<endl;
}
}
return 0;
}