题解:P10467 [CCC 2007] Snowflake Snow Snowflakes

· · 题解

考虑到可以哈希处理。

设计哈希函数,

H(a)=\left(\sum_{i=1}^6a_i+\prod_{i=1}^6a_i\right)\bmod p

取 p 为一大质数,例如 0xccf54188 - 1。

这样,如果两片相同的雪花,其散列值是相同的。

然后设计判断取等的函数,直接模拟即可。

这里使用 unordered_map + 手写哈希实现,

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

constexpr ll P = 0xccf54188 - 1;

#define int ll

struct emm {
    array<int, 6> s;
    friend bool operator ==(const emm &a, const emm &b) {
        auto s = b.s;
        for (int t = 0; t < 6; ++t) {
            if (s == a.s) return 1;
            int e = s[0];
            for (int i = 0; i < 5; ++i) s[i] = s[i + 1];
            s[5] = e;
        }
        reverse(s.begin(), s.end());
        for (int t = 0; t < 6; ++t) {
            if (s == a.s) return 1;
            int e = s[0];
            for (int i = 0; i < 5; ++i) s[i] = s[i + 1];
            s[5] = e;
        }
        return 0;
    }
};

struct my_hash {
    ll operator ()(const emm a) const {
        ll r = 0;
        for (int i : a.s) r = (r + i) % P;
        ll e = 1;
        for (int i : a.s) e = e * i % P;
        return (r + e) % P;
    }
};

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    int n; cin >> n; emm t;
    unordered_set<emm, my_hash> app;
    for (int i = 0; i < n; ++i) {
        for (int &i : t.s) cin >> i;
        if (app.count(t)) puts("Twin snowflakes found."), exit(0);
        app.insert(t);
    } return puts("No two snowflakes are alike."), 0;
}