码迷,mamicode.com
首页 > 其他好文 > 详细

数的hash;

时间:2016-04-01 22:07:55      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

数的hash;

标签:

原文地址:http://www.cnblogs.com/dlut-li/p/5346376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!