El uso de hash poj 3349

La idea de la función hash es una idea muy importante en la búsqueda. En la estructura de datos, solo aprendemos algunas funciones simples

Por ejemplo:

Añadir resto

Multiplica el resto

Dividir por

。。。。

La función hash puede encontrar la ubicación de los datos en O (1) durante la búsqueda.

La clave de la función hash es la elección de la función. Sin embargo, no importa qué tipo de función se seleccione, generalmente habrá conflictos. Sin embargo, si la función se selecciona correctamente, el conflicto se reducirá.


poj 3349 es una simple pregunta hash

La función que seleccionamos es:

Agrega el resto

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

Código:

#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
*/

En el estado de este tema , vi que alguien obtuvo A dentro de 1000 ms, no sé cómo se seleccionó su función hash


190 artículos originales publicados · 19 alabanzas · 200,000+ vistas

Supongo que te gusta

Origin blog.csdn.net/zengchenacmer/article/details/29186213
Recomendado
Clasificación