poj 2503 Babelfish 【hash】

来源:互联网 发布:java 反射 注解 编辑:程序博客网 时间:2024/06/06 15:36

HASH:141MS

#include<cstdio>#include<cstring>#define th(a) this->a=a;const int maxn=100000+10;const int prime=25013;struct Hash{    char *s1,*s2;    Hash *nxt;}hashpool[maxn];Hash *head[prime+1],*ph;char buf[maxn<<1][11];inline unsigned int hash(char *url,int mod=prime){    unsigned int h=0,g;    while(*url)    {        h=(h<<4)+*url++;        if(g=h&0xf0000000) h^=g>>24;        h&=~g;    }    return h%mod;}int main(){    int i,j,poolcnt=0,bufcnt=0,p;    char str[50],*s1,*s2;    while(gets(str)&&str[0])    {        s1=buf[bufcnt],s2=buf[bufcnt+1];        for(i=0;str[i]!=' ';i++)            s1[i]=str[i];        s1[i]=0;        while(str[++i]==' ');        for(j=0;str[i];i++)            s2[j++]=str[i];        s2[j]=0;        p=hash(s2);ph=hashpool+poolcnt++;        ph->s1=s1;ph->s2=s2;ph->nxt=head[p];        head[p]=ph;        bufcnt+=2;    }    while(gets(str)!=NULL)    {        p=hash(str);ph=head[p];        while(ph!=NULL)        {            if(strcmp(str,ph->s2)==0)            {                puts(ph->s1);break;            }            ph=ph->nxt;        }        if(ph==NULL) puts("eh");    }    return 0;}



原创粉丝点击