POJ3349 (Snowflake Snow Snowflakes)[Hash]

·· / ·– ·· ·-·· ·-·· / ·–· · ·-· ··· ·· ··· - / ··- -· - ·· ·-·· / ·· / ·– ·· -·
题目链接:http://poj.org/problem?id=3349
参考博客:Shadowdsp
数据范围比较大,直接两两比较肯定不行,这时候考虑Hash,把雪花每个枝的长度加起来并取模获得Hash值,拥有相同Hash值的雪花暴力比较。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <cstdio>
#include <cstring>
#include <algorithm>
const int MOD = 14997;
struct node {
int len[6];
}snow, f[15000][50];
int Hash[15000];
bool check(node a, node b) {
int i, j, k;
bool flag;
for (i = 0; i < 6; i++) {
flag = true;
for (j=i, k=0; k<6; k++, j=(j+1)%6) {
if (a.len[j] != b.len[k]) {
flag = false;
break;
}
}
if (flag) return 1;
}
for (i = 0; i < 6; i++) {
flag = true;
for (j=i, k=0; k<6; k++, j=(j+5)%6) {
if (a.len[j] != b.len[k]) {
flag = false;
break;
}
}
if (flag) return 1;
}
return 0;
}
int main() {
int n, now;
scanf("%d",&n);
bool flag = false;
for (int i=0; i<n; i++) {
now = 0;
for (int j=0; j<6; j++) {
scanf("%d", &snow.len[j]);
now += snow.len[j] % MOD;
}
if (flag) continue;
now %= MOD;
if (Hash[now]>0) {
for (int j = 1; j<=Hash[now]; j++) {
if (check(snow, f[now][j])) {
flag = true;
break;
}
}
}
Hash[now]++;
f[now][Hash[now]] = snow;
}
if (flag) printf("Twin snowflakes found.\n");
else printf("No two snowflakes are alike.\n");
return 0;
}