zoukankan      html  css  js  c++  java
  • 字符串哈希之散列表处理冲突 poj1880

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define M 100001
    #define N 100
    
    struct node       //链表数组
    {
        int id;
        struct node *next;
    }*d[M];  
    
    char a[M][N],b[M][N]; 
    char s[N],str[N];
    
    unsigned int ELFHash(char *str)
    {
        unsigned int hash=0;
        unsigned int x=0;
        while(*str)
        {
            hash=(hash<<4)+(*str++);
            if((x=hash&0xF0000000L)!=0)
            {
                hash^=(x>>24);
                hash&=~x;
            }
        }
        return hash%M;
    }
    int main()
    {
        int i=0;
        struct node *p;
        while(scanf("%s",str),strcmp("@END@",str)) 
        {
            int len=strlen(str);
            str[len-1]='';
            strcpy(a[i],str+1); //前一个字符串处理
            gets(str);          //后一个字符串处理
            strcpy(b[i],str+1);
            
            int hash=ELFHash(b[i]);  //后一个字符串的映射
            p=(struct node *)malloc(sizeof(struct node));//创建动态链表p
            p->id=i;          //给值
            p->next=d[hash];  //给链表数组的第hash个链表给首地址
            d[hash]=p;        //将链表p的首地址付给链表数组的第hash个链表
            
            hash=ELFHash(a[i]);    //前一个字符串的映射,两个字符串的i值相同
            p=(struct node *)malloc(sizeof(struct node));
            p->id=i;
            p->next=d[hash];
            d[hash]=p;
            i++;
        }
        int n;
        scanf("%d",&n);
        getchar();
        while(n--)
        {
            gets(str);
            if(str[0]=='[')
            {
                int len=strlen(str);
                str[len-1]='';
                strcpy(s,str+1);
            }
            else
                strcpy(s,str);
            int hash=ELFHash(s);
            p=d[hash];
            int flag1=1,flag2=1;
            while(p)
            {
                if(strcmp(b[p->id],s)==0)
                {
                    flag1=0;
                    break;
                }
                if(strcmp(a[p->id],s)==0)
                {
                    flag2=0;
                    break;
                }
                p=p->next;
            }
            if(p)
            {
                if(flag1==0)
                    printf("%s
    ",a[p->id]);
                else
                    printf("%s
    ",b[p->id]);
            }
            else
                printf("what?
    ");
        }
        return 0;
    }
  • 相关阅读:
    hdu 4370
    lightoj 1074
    poj 1026
    poj 3159
    poj3660 cow contest
    hdu 4069 垃圾数独
    操作系统概念题复习
    ARM指令
    C++ 抢占时优先级进程调度
    Docker 入门
  • 原文地址:https://www.cnblogs.com/calmwithdream/p/5351906.html
Copyright © 2011-2022 走看看