程序设计思维与实践 Week15 作业 A - ZJM 与霍格沃兹(必做)

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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值