您的位置:首页 > 其它

poj 3349 哈希 简单拉链(卡时间过去的。。。)

2018-02-24 16:57 323 查看
大家好,昨天由于感觉到hash表作为一种数据结构的强壮能力,决定做些相关题练习一下,所以做了poj3349这一道。简单来看就是问一堆雪花有没有同构的,而在询问的过程中,经本人测试,用log n 时间插入及查询会超时,所以应该运用哈希表才能过去。雪花由于其对称性,可以举出其同构的12种类型,经比较后确定最小值并插入。解决冲突的方法采用了最原始的拉链法,最后3.7s过去的,惊险。别的方法我还会尝试的。#include <iostream>
#include <cstdio>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
#define MAXN 100010
#define HASHMOD 100010
typedef struct ota {
int a[6];
struct ota(int aa[]) {
for (int i = 0; i < 6; i++)
a[i] = aa[i];
}
bool operator == (struct ota bb) {
for (int i = 0; i < 6; i++)
if (a[i] != bb.a[i])
return false;
return true;
}
}Ota;
bool isBigger(int a[], int b[])
{
for (int i = 0; i < 6; i++)
if (a[i] != b[i])
return a[i] > b[i];
return false;
}
vector<Ota > hashTable[MAXN];
void initHash()
{
for (int i = 0; i < MAXN; i++)
hashTable[i].clear();
}
int getHash(int a[])
{
int ret = 0;
for (int i = 0; i < 6; i++) {
ret += a[i];
ret %= HASHMOD;
}
return ret;
}
bool searchHash(int a[])
{
int h = getHash(a);
Ota temp = Ota(a);
if (hashTable[h].size() == 0) {
hashTable[h].push_back(temp);
return true;
}
for (int i = 0; i < hashTable[h].size(); i++) {
if (hashTable[h][i] == temp)
return false;
}
hashTable[h].push_back(temp);
return true;
}
int main()
{
int num[2][12], n;//for storing all possible permutations efficiently
bool twin = false;
initHash();
scanf("%d", &n);
while (n--) {
for (int i = 0; i < 6; i++) {
scanf("%d", &num[0][i]);
num[0][i + 6] = num[0][i];
}
if (twin)
continue;
for (int i = 0; i < 6; i++)
num[1][i + 6] = num[1][i] = num[0][5 - i];
int *tempMin;
tempMin = num[0];
for (int i = 0; i < 6; i++)
if (isBigger(tempMin, num[0] + i))
tempMin = num[0] + i;
for (int i = 0; i < 6; i++)
if (isBigger(tempMin, num[1] + i))
tempMin = num[1] + i;
if (searchHash(tempMin) == false)
twin = 1;
}
if (twin)
printf("Twin snowflakes found.\n");
else
printf("No two snowflakes are alike.\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hash isomorphism