POJ2503

本文深入探讨了哈希算法的应用与优化过程,通过实例分析了如何避免内存不足(MLE)、时间限制(TLE)和运行错误(RE),并介绍了UNIX ELF可执行文件中使用的ELF hash函数。详细阐述了不同哈希方法的选择与实现,包括水过方法、字母加总、字母乘积等,并最终采用ELF hash函数成功解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写了几道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");
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值