問題描述
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<string,string>是絕對不可能過的。一定要用字符串哈希。我是用的unsigned int自然溢出處理的。最後map使用map<unsigned,int>就可以了。
對於這道題,我們建立兩個map<unsigned,int>,unsigned對應的是字符串的哈希值,int對應的是這個字符串存儲的位置。然後查找的時候直接將要查找的字符串哈希一下,看看int是否爲0即可,如果是0,就是找不到,否則就去存儲咒語 / 對應功能的數組裏面找。
但是,如果你用了字符串哈希,你存儲咒語和對應功能的數組是用的string[maxn],那麼也會MLE。所以你必須使用兩個二維char來存。
最後,我還是wa了,然後把seed從131改成17就過了。。。哈希的風險第一次做題就碰到了,愛了愛了。 我錯了,不是seed的問題,我開始的hash函數有一點錯誤,改正後131也能過。
完整代碼
//#pragma GCC optimize(2)
//#pragma G++ optimize(2)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <climits>
#include <algorithm>
#include <queue>
#include <vector>
#include <map>
using namespace std;
const int maxn=1000000+10;
char s1[maxn][25],s2[maxn][85];
int cnt;
map<unsigned,int> mp;
unsigned hashstring(string _s){//BKDR哈希
unsigned int seed=17,_hash=0;
for (int i=0; i<_s.size(); i++)
_hash=_hash*seed+(unsigned)(_s[i]);
return _hash;
}
void split(string _s){
string _s1,_s2;
for (int i=1; i<_s.size(); i++){
if(_s[i]==']'){
_s1=_s2;
_s2.clear();
i++;
continue;
}
_s2+=_s[i];
}
cnt++;
mp[hashstring(_s1)]=cnt; strcpy(s1[cnt],_s1.c_str());
mp[hashstring(_s2)]=cnt; strcpy(s2[cnt],_s2.c_str());
}
void find(string _s){
if(_s[0]=='['){
string snew; snew.clear();
for (int i=1; i<_s.size()-1; i++)
snew+=_s[i];
unsigned _hash=hashstring(snew);
if(mp[_hash]==0){
printf("what?\n");
return;
}
printf("%s\n",s2[mp[_hash]]);
return;
}
else {
unsigned _hash=hashstring(_s);
if(mp[_hash]==0){
printf("what?\n");
return;
}
printf("%s\n",s1[mp[_hash]]);
return;
}
}
int getint(){
int x=0,s=1; char ch=' ';
while(ch<'0' || ch>'9'){ ch=getchar(); if(ch=='-') s=-1;}
while(ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar();}
return x*s;
}
int main(){
//ios::sync_with_stdio(false);
//cin.tie(0);
while(true){
string s; getline(cin,s);
if(s=="@END@") break;
split(s);
}
int n; scanf("%d",&n);
getchar();
while(n--){
string s; getline(cin,s);
find(s);
}
return 0;
}