魔咒問題

題面:

魔咒詞典中有很多魔咒,他們的格式:[魔咒] 對應功能

現在共有 N 個問題,每道題給出一個字符串,可能是 [魔咒],也可能是對應功能

你需要識別這個題目給出的是 [魔咒] 還是對應功能,並寫出轉換的結果,如果在魔咒詞典裏找不到,就輸出 “what?”

輸入首先列出魔咒詞典中不超過100000條不同的咒語,每條格式爲: [魔咒] 對應功能

其中“魔咒”和“對應功能”分別爲長度不超過20和80的字符串,字符串中保證不包含字符“[”和“]”,且“]”和後面的字符串之間有且僅有一個空格。魔咒詞典最後一行以“@END@”結束,這一行不屬於詞典中的詞條。

詞典之後的一行包含正整數N(<=1000),隨後是N個測試用例。每個測試用例佔一行,或者給出“[魔咒]”,或者給出“對應功能”

每個測試用例的輸出佔一行,輸出魔咒對應的功能,或者功能對應的魔咒。如果在詞典中查不到,就輸出“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?

思路:

  • 這道題是一個對字符串進行哈希的題目,使用bkdr將一串字符串進行哈希轉爲一串數字
  • seed常用7,17,131或者其他質數,mod常見取值用1e9+7或採用unsigned long long 自然溢出(相當於%264)
  • 舉例字符串aed : (1 x seed3+5 x seed2 + 4 x seed1)%mod
  • 使用bkdr的特點是,字符變化和兩個字符串合併都可以使用 o(1) 來修改哈希值,可用於快速查詢一個串是否出現過,快速比較兩個串是否相同。同時給定hash值無法還原字符串,比較安全。
  • 本題使用兩個map進行映射,map[hash1] = index, s1[index] = 魔咒 ;map[hash2] = index, s2[index] = 對應功能
  • 對於每一次的查詢都首先用 ‘ [ ’ 來判斷給定的是魔咒還是對應的功能,然後在對應的map中進行查詢
  • 因爲可能會出現其他字符,所以減 ’ ’ 來保證每一個字符都能找到對應的asc碼來計算對應的hash值
  • 需要注意讀入空格的問題和讀入功能有空格的時候應該用getline來讀入
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<map> 
using namespace std;
const int seed=17;
char mz[100001][30],gn[100001][100];
map<unsigned long long ,int>m,g;
int hashash(char *str)
{
 int sum=0;
 int sed=1;
 int len=strlen(str);
 for(int i=0;i<=len;i++)
 {
  sed*=seed;
  sum+=(str[i]-' ')*sed;
 }
 return sum;
}
int main()
{
 string str1,str2,str3;
 int tot=0,n=0;
 char q[1001];
 while(cin>>str1)//遇到空格停止 
 {
  //if(strcmp(str1,'@END@')==0)
  //c++允許直接== 
  if(str1=="@END@")
   break;
  tot++;
  getline(cin,str2);
  strcpy(mz[tot],str1.c_str());
  strcpy(gn[tot],str2.c_str()+1);
  m[hashash(mz[tot])]=tot;
  g[hashash(gn[tot])]=tot;
 }
 scanf("%d",&n);
 getchar();
 for(int i=0;i<n;i++)
 {
  getline(cin,str3);
  strcpy(q,str3.c_str());
  unsigned long long temp=hashash(q);
  if(q[0]=='[')//判斷是什麼內容的查詢 
  {
   if(m.find(temp)==m.end())
    cout<<"what?"<<endl;
   else cout<<gn[m[temp]]<<endl;
  }
  else
  {
   if(g.find(temp)==g.end())
    cout<<"what?"<<endl;
   else
   {
    for(int i=1;i<strlen(mz[g[temp]])-1;i++)
     cout<<mz[g[temp]][i];
    cout<<endl;
   }
  }
 }
 return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章