题意
传送门 POJ 3349
题解
每朵雪花有 12 12 12 种排序,直接 O ( n 2 ) O(n^2) O(n2) 比较复杂度过高。建立 H a s h Hash Hash 表,将 n n n 朵雪花一次插入,扫描其哈希值对应的链表,检查是否存在与其相等的雪花即可。
考虑到雪花循环同构,设雪花角的个数为 l l l,直接比较 2 2 2 朵雪花复杂 O ( l 3 ) O(l^3) O(l3)。将其 O ( l ) O(l) O(l) 预处理为最小表示法,就可以在哈希冲突时 O ( l ) O(l) O(l) 检查 2 2 2 朵雪花是否相等。
定义哈希函数为 H ( a 0 , a 1 , … , a 5 ) = [ ∑ i = 0 5 ( a i + r i ) + ∏ i = 0 5 ( a i + r i ) ] m o d P H(a_0,a_1,\dots,a_5)=[\sum\limits_{i=0}^{5}(a_i+r_i)+\prod\limits_{i=0}^{5}(a_i+r_i)]\mod P H(a0,a1,…,a5)=[i=0∑5(ai+ri)+i=0∏5(ai+ri)]modP,其中 a i , r i a_i,r_i ai,ri 为雪花顺时针、逆时针各角的长度的最小表示法。显然,若两朵雪花相等,其六个角的在最小表示法下顺序确定且相等,其长度之和、长度之积都相等。
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 100005, mod = 99991;
struct snow
{
int a[6], r[6];
} S[maxn];
int N, tot, head[maxn], nxt[maxn];
int hash(snow &x)
{
int s = 0, m = 1;
for (int i = 0; i < 6; ++i)
s = (s + x.a[i] + x.r[i]) % mod, m = (long long)m * (x.a[i] + x.r[i]) % mod;
return (s + m) % mod;
}
void op(int *a, int *s)
{
int b[12];
for (int i = 0; i < 6; ++i)
b[i] = b[i + 6] = a[i];
int i = 0, j = 1, k;
while (i < 6 && j < 6)
{
for (k = 0; k < 6 && b[i + k] == b[j + k]; ++k)
;
if (k == 6)
break;
if (b[i + k] > b[j + k])
i = i + k + 1, i += i == j;
else
j = j + k + 1, j += j == i;
}
int p = min(i, j);
memcpy(s, b + p, sizeof(int) * 6);
}
bool equa(snow &a, snow &b)
{
bool f = 1;
for (int i = 0; i < 6; ++i)
if (a.a[i] != b.a[i])
f = 0;
if (f)
return 1;
f = 1;
for (int i = 0; i < 6; ++i)
if (a.a[i] != b.r[i])
f = 0;
return f;
}
bool insert(int *a)
{
snow &s = S[++tot];
op(a, s.a);
reverse(a, a + 6);
op(a, s.r);
int h = hash(s);
for (int i = head[h]; i; i = nxt[i])
if (equa(S[i], s))
return 1;
nxt[tot] = head[h], head[h] = tot;
return 0;
}
int main()
{
scanf("%d", &N);
while (N--)
{
int a[6];
for (int i = 0; i < 6; ++i)
scanf("%d", a + i);
if (insert(a))
{
puts("Twin snowflakes found.");
return 0;
}
}
puts("No two snowflakes are alike.");
return 0;
}