poj3349 Snowflake Snow Snowflakes

吼哇!

关于开散列哈希

哈希就是把xxx对应到一个数字的东西,可以理解成一个map<xxx, int>(是不是比喻反了)

我们要设计一个函数,这个函数要确保同一个东西能得到相同的函数值(废话)

然后在函数值域上开邻接表即可。

本人第一次写hash,还不是经典字符串hash而是雪花雪雪花(......)

那么接下来欣赏丑陋不堪的hash吧!

(poj上C++过不了,RE,G++就过了,有剧毒)

 1 #include <cstdio>
 2 const int N = 1000010, P = 99991;
 3 
 4 int a[10];
 5 
 6 struct Snowflake {
 7     int a[6];
 8     bool operator == (const Snowflake &x) const {
 9         for(int i = 0; i < 6; i++) { /// 从i/0开始
10             bool f = 1;
11             for(int j = 0; j < 6; j++) {
12                 if(a[(j + i) % 6] != x.a[j]) {
13                     f = 0;
14                 }
15             }
16             if(f) return 1;
17             f = 1;
18             for(int j = 0; j < 6; j++) {
19                 if(a[(j + i) % 6] != x.a[(6 - j) % 6]) {
20                     f = 0;
21                 }
22             }
23             if(f) return 1;
24         }
25         return 0;
26     }
27 }s[N];
28 
29 struct Hashnode {
30     int p, nex;
31 }h[N]; int top;
32 int head[P];
33 
34 inline int gethash(Snowflake x) {
35     int ans = 0;
36     for(int i = 0; i < 6; i++) {
37         ans = (ans + x.a[i]) % P;
38         ans = (ans + (x.a[i] % P) * (x.a[(i + 1) % 6] % P)) % P;
39     }
40     return ans;
41 }
42 
43 inline bool inserthash(int x) {
44     int val = gethash(s[x]);
45     for(int i = head[val]; i; i = h[i].nex) {
46         if(s[x] == s[h[i].p]) return 1;
47     }
48 
49     top++;
50     h[top].p = x;
51     h[top].nex = head[val];
52     head[val] = top;
53     return 0;
54 }
55 
56 int main() {
57     //freopen("in.in", "r", stdin);
58     int n, x;
59     scanf("%d", &n);
60     for(int i = 1; i <= n; i++) {
61         for(int j = 0; j < 6; j++) {
62             scanf("%d", &s[i].a[j]);
63         }
64         if(inserthash(i)) {
65             printf("Twin snowflakes found.\n");
66             return 0;
67         }
68     }
69     printf("No two snowflakes are alike.\n");
70     return 0;
71 }
AC代码

 

posted @ 2018-05-19 18:01  garage  阅读(100)  评论(0编辑  收藏  举报