较大数的hash算法

来源:互联网 发布:汇丰软件开发 待遇 编辑:程序博客网 时间:2024/04/30 14:28

1.数的哈希一般是讲较大的数转化为一定范围内的数,如112131321321 转化为100000以内,一般用%99991;就是自己构造hash函数,然后函数值在100000以内;

2.当出现相同的key值,即函数值时,要用链表串起;

3.例:poj 3349;

#include<iostream>#include<stdio.h>using namespace std;const int prime=99991;int map[100100][10];struct Node{    int x;    Node *next;} hash[100000];bool check(int x,int y){    int i,j;    bool flag=false;    for (i=0;i<=5;i++)    {        bool flag1 =true;        for(j=1;j<=6;j++)            if(map[x][j]!=map[y][(j+i-1)%6+1]) flag1=false;        if(flag1) flag=true;        flag1=true;        for (j=1;j<=6;j++)            if(map[x][7-j]!=map[y][(j+i-1)%6+1]) flag1=false;         if(flag1) flag=true;    }    return flag;}bool assemble(int j,int key){    Node *p=&hash[key];    while (p->next!=NULL)    {        if(check(p->x,j)) return true;        p=p->next;    }    if(check(p->x,j)) return true;    Node *p1=new Node;    p1->x=j;    p1->next=NULL;    p->next=p1;    return false;}bool insert(int j){    int sum=0,i;    for (i=1;i<=6;i++)        sum+=map[j][i]%prime;    sum%=prime;    if(hash[sum].x==0) {        hash[sum].x=j;        return true;    }else if(!assemble(j,sum))     return true;  return false;}int main(){    int n,i,j;    bool flag=true;    cin>>n;    for (i=1;i<=99991;i++) { hash[i].x=0;hash[i].next=NULL;}    for (i=1;i<=n;i++)    {        for(j=1;j<=6;j++)            scanf("%d",&map[i][j]);        if(flag)            if(!insert(i))            flag=false;    }    if(flag)        printf("No two snowflakes are alike.\n");    else printf("Twin snowflakes found.\n");    return 0;}


0 0