POJ3349 Snowflake Snow Snowflakes 哈希表

Posted Mychael

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ3349 Snowflake Snow Snowflakes 哈希表相关的知识,希望对你有一定的参考价值。

题目

很简单,给一堆6元组,可以从任意位置开始往任意方向读,问有没有两个相同的6元组

题解

hash表入门题
先把一个六元组的积 + 和取模作为hash值,然后查表即可
期望\(O(n)\)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u]; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
using namespace std;
const int maxn = 100010,maxm = 100005,INF = 1000000000,P = 100007;
inline int read(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57){if (c == ‘-‘) flag = -1; c = getchar();}
    while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
    return out * flag;
}
int h[maxn],nxt[maxn],n,tot;
LL A[6],H[maxn][6];
bool cmp(LL A[],LL B[]){
    for (int pos = 0; pos < 6; pos++){
        bool flag = true;
        for (int i = 0; i < 6; i++)
            if (A[i] != B[(pos + i) % 6]){
                flag = false; break;
            }
        if (flag) return true;
        flag = true;
        for (int i = 0; i < 6; i++)
            if (A[i] != B[(pos - i + 6) % 6]){
                flag = false; break;
            }
        if (flag) return true;
    }
    return false;
}
bool ins(){
    LL s = 0,m = 1,v;
    for (int i = 0; i < 6; i++)
        s = (s + A[i]) % P,m = m * A[i] % P;
    v = (s + m) % P;
    for (int k = h[v]; k != -1; k = nxt[k])
        if (cmp(H[k],A)) return true;
    tot++;
    for (int i = 0; i < 6; i++) H[tot][i] = A[i];
    nxt[tot] = h[v]; h[v] = tot;
    return false;
}
int main(){
    memset(h,-1,sizeof(h));
    n = read();
    for (int i = 1; i <= n; i++){
        for (int j = 0; j < 6; j++)
            A[j] = read();
        if (ins()) {puts("Twin snowflakes found."); return 0;}
    }
    puts("No two snowflakes are alike.");
    return 0;
}

以上是关于POJ3349 Snowflake Snow Snowflakes 哈希表的主要内容,如果未能解决你的问题,请参考以下文章

POJ 3349 -- Snowflake Snow Snowflakes

POJ 3349 Snowflake Snow Snowflakes

poj3349 Snowflake Snow Snowflakes(HASH)

哈希—— POJ 3349 Snowflake Snow Snowflakes

POJ3349 Snowflake Snow Snowflakes(Hash)

POJ 3349:Snowflake Snow Snowflakes(数的Hash)