写了几道hash的题目,结果都是水过的。只有这一道老老实实的用链表,用折叠法(完全看不懂这代码)。最开始想水过,结果MLE。后来想的是将所有的字母全部加起来然后hash,结果TLE了,后来又想尝试着将所有的字母乘起来然后mod一个素数。结果RE了。心如槁灰。于是看DISCUSS,又看到人这个hash方法,貌似我前面水过的2002也是这样做。据知这个函数用于UNIX的ELF可执行文件。这道题还有很不爽的就是它的输入。不过学习了。
上代码:
/*int ELFhash(char * key)
{
unsigned int h = 0;
while (*key){
h = (h << 4) + *key++;
unsigned int g = h & 0xf0000000L;
if (g) h ^= g >> 24;
h &= ~g;
}
return h % prime;
}*/
#include<cstdio>
#include<cstring>
using namespace std;
struct node{
char a[11];
char b[11];
node *nextp;
};
node c[1010];
char e[20],f[20],q[20];
int ELFhash(char * key)
{
unsigned int h = 0;
while (*key){
h = (h << 4) + *key++;
unsigned int g = h & 0xf0000000L;
if (g) h ^= g >> 24;
h &= ~g;
}
return h % 1001;
}
main(){
int i=0,j,k,flag;
char cnt[30];
while(gets(cnt) && strcmp(cnt,"")!=0){
sscanf(cnt,"%s%s",e,f);
int key=1;
key=ELFhash(f);
node *temp=&c[key];
node *point;
point=new node;
strcpy(point->a,e);
strcpy(point->b,f);
point->nextp=NULL;
while(temp->nextp!=NULL)
temp=temp->nextp;
temp->nextp=point;
}
while(gets(q)){
if(strcmp(q,"")==0){
break;
}
else{
int key=1;
key=ELFhash(q);
node* temp=&c[key];
flag=0;
while(temp->nextp!=NULL){
temp=temp->nextp;
if(strcmp(temp->b,q)==0){
flag=1;
printf("%s\n",temp->a);
break;
}
}
if(flag==0){
printf("eh\n");
}
}
}
}
POJ2503
最新推荐文章于 2019-08-11 17:32:56 发布