魔咒词典
Time Limit: 8000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18839 Accepted Submission(s): 4398
Problem Description
哈利波特在魔法学校的必修课之一就是学习魔咒。据说魔法世界有100000种不同的魔咒,哈利很难全部记住,但是为了对抗强敌,他必须在危急时刻能够调用任何一个需要的魔咒,所以他需要你的帮助。
给你一部魔咒词典。当哈利听到一个魔咒时,你的程序必须告诉他那个魔咒的功能;当哈利需要某个功能但不知道该用什么魔咒时,你的程序要替他找到相应的魔咒。如果他要的魔咒不在词典中,就输出“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,但让字符串(咒语)映射字符串(功能),会出现超内存的问题,所以就采用字符串哈希处理。
将字符串通过哈希函数转化为整数,从而用整数映射字符串,达到压缩使用空间的效果。由于用哈希函数得到的这样的映射不一定是入射,也就是可能有不同的x对应相同的f(x),所以采用两个不同哈希函数得到两个整数,用这个整数对作为这个字符串的映射,从而大大减小了重复的几率,也就可以在数据量还不是特别大的时候,能使每个整数对对应的字符串是不同的。
做两个map<pair<int,int>,string>,就可以把咒语、功能相互转化了。
代码如下
#include<iostream>
#include<cstdio>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int mod=1e5+7;
const int N=105;
const int base1=13;
const int base2=131;
int h1(char *s){
int k,ans;
k=0;
ans=0;
while(s[k])
ans=(ans*base1+s[k++])%mod;
return ans;
}
int h2(char *s){
int k,ans;
k=0;
ans=0;
while(s[k])
ans=(ans*base2+s[k++])%mod;
return ans;
}
char str[N];
char A[N];
char B[N];
int main(){
map<pair<int,int>,string> curse;
map<pair<int,int>,string> function;
int i,j,len,s[4];
while(gets(str)){
if(str[0]=='@') break;
len=strlen(str);
for(i=1,j=0;str[i]!=']';i++,j++){
A[j]=str[i];
}
A[j]='\0';
for(i+=2,j=0;i<len;i++,j++){
B[j]=str[i];
}
B[j]='\0';
s[0]=h1(A);
s[1]=h2(A);
s[2]=h1(B);
s[3]=h2(B);
function[make_pair(s[0],s[1])]=B;
curse[make_pair(s[2],s[3])]=A;
}
int t;
scanf("%d",&t);
getchar();
while(t--){
int i,j,len;
gets(str);
len=strlen(str);
for(i=j=0;i<len;i++){
if(str[i]=='['||str[i]==']') continue;
A[j++]=str[i];
}
A[j]='\0';
s[0]=h1(A);
s[1]=h2(A);
string temp;
if(str[0]=='[') temp=function[make_pair(s[0],s[1])];
else temp=curse[make_pair(s[0],s[1])];
if(temp=="") printf("what?\n");
else printf("%s\n",temp.c_str());
}
return 0;
}

本文介绍了一种利用哈希函数压缩空间的方法,通过将字符串转化为整数,实现咒语与功能之间的高效互查。针对《哈利·波特》中的魔法词典问题,采用双哈希函数确保映射唯一性,避免内存溢出,适用于数据量适中的场景。
661

被折叠的 条评论
为什么被折叠?



