样例
input:
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay
atcay
ittenkay
oopslay
output:
cat
eh
loops
思路:
这里用的是最一般的hash写法,效率相对低
tips:
1.gets在处理时遇到回车或者文件末尾才停止,所以需要把两个字符串分开
同时也需要注意s的数组要开的大一点不然就会导致数组越界
2.gets()的返回值时NULL
3.用线性探测法时要注意把hash的数组开大一点,拿空间来换时间,尽量减少冲突。
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=11111111;
int maxx=-0x3f3f3f3f;
char s[111],t[111],m[maxn+5][11],mm[maxn+5][11],none[111]="eh";
int getha(char s[])
{
int l=strlen(s);
int ha=0;
for(int i=0;i<l;i++)
{
ha=(ha*233LL+s[i])%998244353;
}
return ha%maxn;
}
void insert(char s[],char t[])
{
int ha=getha(t);//cout<<"s="<<s<<" "<<"ha="<<ha<<endl;
int ls=strlen(s),lt=strlen(t);
while(m[ha][0]!=0)
{
ha++;
ha%=maxn;
}
for(int i=0;i<lt;i++)
{
m[ha][i]=t[i];
}
for(int i=0;i<ls;i++)
{
mm[ha][i]=s[i];
}
//cout<<"!!"<<m[ha]<<" "<<mm[ha]<<endl;
}
void query(char s[])
{
int ha=getha(s);//cout<<"s="<<s<<endl;
while(m[ha][0]&&strcmp(s,m[ha])!=0)
{
ha++;
ha%=maxn;
}
if (!m[ha][0])
{
cout<<none<<endl;
return;
}
if((strcmp(s,m[ha]))==0)
{
cout<<mm[ha]<<endl;
return;
}
}
int main()
{
int flag=0,pos;
while (gets(s)!=NULL)
{
if(s[0]==0)
{
flag=1;
continue;
}
if(flag==0)
{
int l=strlen(s);
for(int i=0;i<l;i++)
{
if (s[i]==' ')
{
pos=i;
break;
}
}
s[pos]=0;
for (int i=pos+1;i<l;i++) t[i-pos-1]=s[i];
t[l-pos-1]=0;
insert(s,t);
}
if(flag)
{
query(s);
}
}
return 0;
}
大佬的stl写法:
#include <bits/stdc++.h>
using namespace std;
string s,t;
unordered_map<string,string> m;
int main()
{
bool flag=false;
while (getline(cin,s))
{
if (s=="") {flag=true;continue;}
if (flag)
{
if (m.find(s)==m.end())
cout<<"eh"<<endl;
else cout<<m[s]<<endl;
}
else
{
stringstream ss{s};
ss>>t;
string temp;
ss>>temp;
m[temp]=t;
}
}
return 0;
}