POJ-3349 简单哈希表的应用

题目大意:

大概就是说,输入n组数据,每组数据6个,如果n组数据中存在两组数据完全相等(数据顺序忽略)
比如
1 2 3 4 5 6 
3 2 1 4 5 6
这两组数据就是相等的

算法分析:

这道题的数据量很大,如果只是暴力遍历的话,很容易超时。所以可以使用哈希表来查询。
哈希表的优点在于查询速度快,缺点在于储存时容易地址冲突。
所以需要优化。
这里我使用的时开散列法,就是说,哈希表储存的节点是链表(数组)。

代码:

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

using namespace std;

struct node
{
    int side[6];
};

node hash_[15000][1000];
int top[15000];     // the count of hash_[index]

int getKey(node& demo) {
    long long key = 0;
    for (int i = 0; i < 6; i++)
        key += demo.side[i];
    key %= 14997;
    return (int)key;
}

bool cmp(node first, node second) {
    sort(first.side, first.side+6);
    sort(second.side, second.side+6);
    for (int i = 0; i < 6; i++) {
        if (first.side[i] != second.side[i])
            return false;
    }
    return true;
}

int main()
{
    int n, tmpKey;
    node tmp;

    scanf("%d", &n);
    memset(top, 0, sizeof(top));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 6; j++) {
            scanf("%d", &tmp.side[j]);
        }
        tmpKey = getKey(tmp);
        for (int j = 0; j < top[tmpKey]; j++) {
            if (cmp(hash_[tmpKey][j], tmp)) {
                printf("Twin snowflakes found.\n");
                return 0;
            }
        }
        hash_[tmpKey][top[tmpKey]++] = tmp;
    }
    printf("No two snowflakes are alike.\n");

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值