The use of poj 3349 hash

The hash function idea is a very important idea in searching. In the data structure, we only learn some simple functions

such as:

Add remainder

Multiply the remainder

Divide by

。。。。

The hash function can find the location of the data in O (1) time during the search.

The key to the hash function is the choice of function. However, no matter what kind of function is selected, there will generally be conflicts. However, if the function is properly selected, then the conflict will be reduced.


poj 3349 is a simple hash question

The function we selected is:

Add the remainder

sort(b , b+6 );
            x = 0;
            for(j = 0; j < 6; j++)
                x = (x*10 + b[j])%maxn;

Code:

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>

using namespace std;

#define maxn 137373

int ha[maxn] , next1[maxn];
int n;
int ya[maxn][6];

void init()
{
    memset(ha , -1 , sizeof(ha));
    memset(next1 , -1 , sizeof(next1));
}

bool make1(int s , int t)
{
    int i , a = 0, j , k;
    int begin1[6];
    for(i = 0; i < 6; i++)
        if(ya[t][i] == ya[s][0])  begin1[a++] = i;
    for(k = 0; k < a; k++)
    {
        j = begin1[k];
        for(i = 0; i < 6; i++)
        {
            if(ya[s][i] == ya[t][j])
            {
                j += 1;
                j = j==6?0:j;
            }
            else break;
        }
        if(i >= 6)  return true;

        j = begin1[k];
        for(i = 0; i < 6; i++)
        {
            if(ya[s][i] == ya[t][j])
            {
                j -= 1;
                j = j<0?5:j;
            }
            else break;
        }
        if(i >= 6)  return true;
    }

    return false;
}

bool check(int s , int x)
{
    int i ;
    if(ha[x] == -1)
    {
        ha[x] = s;
        return false;
    }

    for(i = ha[x] ; i != -1; i = next1[i])
    {
        if(make1(s , i)) return true;
    }

    next1[s] = ha[x];
    ha[x] = s;
    return false;
}

int main()
{
    while(scanf("%d" , &n) != EOF)
    {
        init();
        int i , j , b[6];
        int x;
        bool bz = false;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < 6; j++)
            {
                scanf("%d" , &ya[i][j]);
                b[j] = ya[i][j];
            }
            if(bz)  continue;
            sort(b , b+6 );
            x = 0;
            for(j = 0; j < 6; j++)
                x = (x*10 + b[j])%maxn;
            bz = check( i , x);
        }
        if(bz)  printf("Twin snowflakes found.\n");
        else printf("No two snowflakes are alike.\n");
    }
    return 0;
}
/*
2
1 2 3 4 5 6
5 6 1 2 3 4
*/

In the status of this topic , I saw that someone got A within 1000ms, I do n’t know how their hash function was selected


Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/29186213