POJ 3349 Snowflake Snow Snowflakes

本文介绍了一种通过哈希方法验证六边形雪花图案唯一性的算法。该算法将六个数值特征相加并对一个大质数取模,以减少哈希冲突的概率。通过对比不同雪花图案的特征,判断是否存在相同的雪花。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本题有各种各样的hash方法。

本菜用的是“把6个数加起来,mod 100001,如果有冲突就放进链表,方便以后比较”。

注意:mod的数最好是一个质数,为什么呢? 看对话

本菜 2012-11-17 10:11:09
为什么那些hash求key的时候,都要mod一个大质数唉?
aikilis大神 2012-11-17 10:11:31
你mod其他数也行
 aikilis大神2012-11-17 10:11:46
质数可以降低碰撞概率
 aikilis大神2012-11-17 10:12:26
你想两个数x,y。他们模一个质数同余的可能性更小
呵呵。。就是这样
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <vector>
using namespace std;
struct T
{
    int a[6];
};
vector<T> hash[100001];
bool judge(T a, T b)
{
    int i;

    for (i=0; i<6; i++)
    {
        if (a.a[0] == b.a[i]
         && a.a[1] == b.a[(i+1)%6]
         && a.a[2] == b.a[(i+2)%6]
         && a.a[3] == b.a[(i+3)%6]
         && a.a[4] == b.a[(i+4)%6]
         && a.a[5] == b.a[(i+5)%6])
            return true;
        if (a.a[0] == b.a[i]
         && a.a[1] == b.a[(i+5)%6]
         && a.a[2] == b.a[(i+4)%6]
         && a.a[3] == b.a[(i+3)%6]
         && a.a[4] == b.a[(i+2)%6]
         && a.a[5] == b.a[(i+1)%6])
            return true;
    }
    return false;
}
int main()
{
    int n,i,t[6],ans,j,k,th;
    T tb;
    scanf("%d",&n);
    ans=0;
    for (i=0; i<100001; i++)
        hash[i].clear();
    for (i=0; i<n; i++)
    {
        th=0;
        for (j=0; j<6; j++)
        {
            scanf("%d",&tb.a[j]);

            th+=tb.a[j];
        }
        if (ans == -1)
            continue;
        th%=100001;
        if (hash[th].size() == 0)
            hash[th].push_back(tb);
        else
        {
            for (j=0; j<hash[th].size(); j++)
            {
                if (judge(tb,hash[th][j]) == true)
                {
                    ans=-1;
                    break;
                }
            }
            if (ans != -1)
                hash[th].push_back(tb);
        }

    }
    if (ans == -1)
        printf("Twin snowflakes found.\n");
    else
        printf("No two snowflakes are alike.\n");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值