【字符串哈希】A - ZJM 与霍格沃兹(必做)
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?
思路
先将字符串转化为hash值,再用map进行hash值与index的一一映射,再将index对应的字符串存在a[index]数组中
记住常用的mod与seed的值(1e9+7与7)
这里对于英文和翻译采用两个map进行存储也可以使用一个进行存储
Answer
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
using namespace std;
const int mod=1e9+7;
const int seed=7;
string s,s1,s2,a1[100100],a2[100100];
map<int,int> m1,m2;
int n,hash0,hash1,hash2,index;
int quick_pow(int x,int k){
int ans=1;
while(k){
if(k&1) ans=(ans*x)%mod;
k>>=1;
x=(x*x)%mod;
}
return ans;
}
int Hash(string s){
int ans=0,n=s.size();
for(int i=n;i>0;i--)
ans=(ans+s[n-i]*quick_pow(seed,i))%mod;
return ans;
}
int main(){
while(1){
getline(cin,s);
if(s=="@END@")break;
s1=s.substr(1,s.find(']')-1);
hash1=Hash(s1);
s2=s.substr(s.find(']')+2,s.size()-s.find(']')-2);
hash2=Hash(s2);
m1[hash1]=index;
a1[index]=s2;
m2[hash2]=index;
a2[index]=s1;
index++;
}
cin>>n;
getchar();//吃掉回车,否则下面getline吃回车
for(int i=1;i<=n;i++){
getline(cin,s);
if(s[0]=='['){
s=s.substr(1,s.find(']')-1);
hash0=Hash(s);
if(m1[hash0])cout<<a1[m1[hash0]]<<endl;
else cout<<"what?"<<endl;
}
else{
hash0=Hash(s);
if(m2[hash0])cout<<a2[m2[hash0]]<<endl;
else cout<<"what?"<<endl;
}
}
return 0;
}
expD - 瑞瑞爱上字符串
瑞瑞最近迷上了字符串,因此决定出一个字符串的题。
给定两个正整数 N、K,考虑所有由 N - 2 个 a 和 2 个 b 组成的字符串,要求输出其中字典序第 K 小的。
例如当 N = 5 时,共有如下 10 种组成方式:
aaabb
aabab
aabba
abaab
ababa
abbaa
baaab
baaba
babaa
bbaaa
Input
多组数据,第一行给定 T,表示数据组数。(1 ≤ T ≤ 1e4)
对于每组数据,给出两个正整数 N、K。(3 ≤ N ≤ 1e5, 1 ≤ K ≤ min(2e9, N * (N-1) / 2 ))
N 的总和不会超过 1e5。
Output
对于每组数据,输出长度为 N 的字典序第 K 小的字符串。
Example
Input
7
5 1
5 2
5 8
5 10
3 1
3 2
20 100
Output
aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa
思路
k的值 两个b的位置
1 11
2 101
3 110
4 1001
5 1010
6 1100
7 10001
8 10010
9 10100
10 11000
第一个b的位置是每1个2个3个…是一层,每层是一样的,所以只需要找到所在的层数就能找到b1,再找到b2在这一层中的位置即可
Answer
#include<iostream>
using namespace std;
int t,n,k,b1,b2;
int main(){
cin>>t;
while(t--){
cin>>n>>k;
for(int i=0,j=1;;j++){
if(i+j>=k){
b1=j+1;//第一个b的位置
b2=k-i;//第二个b的位置
break;
}
i+=j;
}
for(int i=n;i>0;i--){
if(i==b1||i==b2)cout<<'b';
else cout<<'a';
}
cout<<endl;
}
}