Week15 作业A - ZJM 与霍格沃兹

题目描述

给出一系列二元组:[原字符串] 翻译字符串;
进行若干次查询,给出原字符串或翻译字符串,输出对应的翻译字符串或原字符串。

输入

首先给出若干行,每行一个二元组:[原字符串] 翻译字符串;
最后一行以"@END@"结尾;
之后一行给出一个整数q,表示询问次数;
之后q行,每行一个[原字符串]或翻译字符串;

输出

输出q行,每行输出对应字符串。

输入样例

[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?

基本思路

该题直接利用map建立字符串到字符串的映射会导致MLE,因此,应当使用hash函数建立字符串到整数的映射,将所有的字符串存入一个数组,再利用map建立hash(字符串)到对应字符串的数组索引的映射。

hash函数的实现如下:

long long _hash(string &st)
{
	long long v=0;
	for(int i=0, l=st.length();i<l;i++)
	{
		v = (v + (long long)(st[i])*seed) %mod;
		v = v*seed % mod; 
	}
	return v;
}

需要注意的点

  • hash值可能会比较大,所以最好使用longlong存储;
  • 为了防止hash值过大导致溢出,应该边计算hash边取模;
  • seed相当于计算hash的一个参数,不宜取的太小,并且要是质数。

完整代码

#include<iostream>
#define seed 131
#define mod 1000000007
#include<string>
#include<map>
#include<vector>
using namespace std;
vector<string> s;
int idx;
map<long long, int> mp;
long long _hash(string &st)
{
	long long v=0;
	for(int i=0, l=st.length();i<l;i++)
	{
		v = (v + (long long)(st[i])*seed) %mod;
		v = v*seed % mod; 
	}
	return v;
}
int main ()
{
	string k, v, line;
	while(true)
	{
		getline(cin, line);
		if(line == "@END@")	break;
		k = line.substr(0, line.find("] ")+1);
		v = line.substr(line.find("] ")+2, line.length() - line.find("] ") - 1);
		s.push_back(v);mp.insert({_hash(k), idx++});
		s.push_back(k);mp.insert({_hash(v), idx++});
	}
	int n;
	cin>>n;
	getchar();
	string q;
	string res;
	for(int i=0;i<n;i++)
	{
		getline(cin, q);
		if(mp.find(_hash(q)) == mp.end())	cout<<"what?"<<endl;
		else
		{
			res = s[mp[_hash(q)]];
			if(res[0] == '[')	res = res.substr(1, res.length() - 2);
			cout<<res<<endl;
		}
		 
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值