您的位置:首页 > 其它

POJ-3349 简单哈希表的应用

2016-10-12 20:42 211 查看

题目大意:

大概就是说,输入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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: